1 回答

TA貢獻1860條經(jīng)驗 獲得超8個贊
基本上,setState() 是異步工作的。因此,您需要等待幾納秒才能獲得該值。您可以通過2種方式做到這一點。
1. 使用等待
componentWillMount() {
await this._fetchData()
alert(this.state.openSellOffers)
}
_fetchData = async () => {
let openSellOffersRes = await fetchOpenSellOffers()
for (let sellOffer of openSellOffersRes.orders) {
let sellObj = {
_id: sellOffer._id,
currencyValue: sellOffer.currencyValue,
unitPrice: sellOffer.unitPrice,
totalPrice: sellOffer.totalPrice,
type: 'sell'
}
this.setState({
openSellOffers: [...this.state.openSellOffers, sellObj]
})
}
return true;
}
**2.使用設(shè)置超時 **
componentWillMount() {
this._fetchData()
setTimeout(() => {
alert(this.state.openSellOffers)
}, 100)
}
_fetchData = async () => {
let openSellOffersRes = await fetchOpenSellOffers()
for (let sellOffer of openSellOffersRes.orders) {
let sellObj = {
_id: sellOffer._id,
currencyValue: sellOffer.currencyValue,
unitPrice: sellOffer.unitPrice,
totalPrice: sellOffer.totalPrice,
type: 'sell'
}
this.setState({
openSellOffers: [...this.state.openSellOffers, sellObj]
})
}
}
添加回答
舉報