[英]How to return React element from an promise result?
我有一個訂單數組,想在數組內部循環並調用異步函數檢查每個訂單,然后在dom.dow中渲染該數組.dow是我的代碼
我嘗試在映射之外創建一個數組並將有效訂單推入該數組,但是當我將其記錄為空
renderTrades = () => {
const { trades } = this.props;
const contractWrappers = new ContractWrappers(web3Wrapper._provider, { networkId: KOVAN_NETWORK_ID });
const _trade = [];
trades.map((trade, index) => {
contractWrappers.exchange.getOrderInfoAsync(trade.order)
.then((val) => {
if (val.orderStatus == 5) {
_trade.push(<TradeRow0x key={index} />);
}
});
});
return _trade;
};
我想將有效訂單推送到數組並將其渲染到dom中
可以使用Promise.all()
在返回所需的JSX之前等待所有諾言解決。
// map all of your trades to promises
const tradesPromises = trades.map(trade => contractWrappers.exchange.getOrderInfoAsync(trade.order))
Promise.all(tradesPromises).then(res => {
// all of your promises have now resolved, so you can return your jsx as required.
const mappedTrades = res.map((value, index) => {
return value.orderStatus === 5 ? <TradeRow key={index} /> : null
})
// now you will be able to log these out and see what you are
// expecting as the promises will all have resolved.
console.log(mappedTrades);
})
有關Promise.all
的詳細說明和示例,請參見https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.