我有一个应用程序需要从 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/