javascript - React - 在获取数据后设置状态时渲染 HTML

标签 javascript reactjs

我有一个应用程序需要从 Stripe API(支付处理器)获取发票数据。返回发票数据后,我尝试使用 this.setState({invoiceData:invoices}) 更新我的状态,其中 invoices 是我的 HTML 字符串根据 Stripe API 返回的数据进行构建。

问题在于 HTML 未呈现并显示为纯文本。我对 React 还很陌生,而且刚刚了解渲染状态,但现在我一直致力于解决这个问题。我需要做什么来呈现 HTML?请参阅下面我的代码。

import React from 'react';

class BillingInvoices extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            invoiceData: false
        }
    }

    // When the 'BillingInvoices' component is mounted:
    componentDidMount() {

        // Get invoice data from Stripe API.
        fetch('/stripe-invoices', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                customerId: '128973982'
            })
        })
        .then((response) => {
            if (response.ok) {
                return response.json();
            } else {
                console.log('Error with Stripe response');
            }
        })
        .then((stripeData) => {

            var invoiceCount = stripeData['result']['data'].length;
            var i;
            var invoices = '';

            for (i = 0; i < invoiceCount; i++) {
                invoices += '<div><a href="' + stripeData['result']['data'][i]['invoice_pdf'] + '" download>' + stripeData['result']['data'][i]['number'] + '</a></div>';
            }

            this.setState({
                invoiceData: invoices
            })
        })
        .catch((error) => {
            console.log('Error: ', error);
        });
    }

    render() {
        return (
            <div id="billing-invoices">
                {this.state.invoiceData ? this.state.invoiceData : null}
            </div>
        );
    }
}

export default BillingInvoices;

感谢您的见解。

最佳答案

我在我的示例中删除了一些代码,以便于阅读:

class BillingInvoices extends React.Component {

  constructor(props) {
    super(props);
    this.state = { invoiceData: [] }
  }

  componentDidMount() {
    fetch('/stripe-invoices')
      .then((response) => response.ok && response.json())

      // Here I'm assigning the nested array to `invoiceData` immediately
      // so that you don't need to map over it later
      .then((data) => this.setState({ invoiceData:  data.result.data }));
  }

  render() {

    // Here we can check if the data exists. If it doesn't
    // show a loading icon (or something) until it is
    if (!this.state.invoiceData) <Loader />

    // ...otherwise show the data
    return (
      <div id="billing-invoices">

        // we map over the invoice data and for each invoice
        // return JSX (your div with an anchor populated with that invoice data)
        {this.state.invoiceData.map((invoice) => {
          return (
            <div>
              <a href={invoice.invoice_pdf} download>{invoice.number}</a>
            </div>
          )
        })}
      );
      </div>
    )
  }
}

关于javascript - React - 在获取数据后设置状态时渲染 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52720165/

相关文章:

javascript - 无法导入工作,JavaScript w/ReactJS & ES6/ES2016

reactjs - VS Code 中的 create-react-app 在 Windows 上抛出未经授权的访问

reactjs - 如何使 React Native FlatList 的 ListHeaderComponent 具有粘性?

javascript - React - (嵌套) Prop 类型无效;它必须是一个函数

javascript - 如何使用 angularjs 进行 ng-repeat 过滤器?

javascript - PHP 中的 HTTPPost 到 JSON

javascript - 如何使用 Highcharts 从数据库传入一系列数据来制作多个 Y 轴

javascript - Nextjs 重新加载页面时获取数据

javascript - 在React中制作“编辑详细信息”组件的正确/首选方式是什么?

javascript - 需要使用 mongoose 更新对象内的值