无法读取在函数中定义的状态值。

问题描述 投票:0回答:1

我试图从一个API中获取一些数据,并将其中的一个数组存储在状态中,然后再在 componentWillMount()! 但是,当我尝试输入上述状态值时,我得到了undefined。

这是我的代码。

componentWillMount() {

        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]
            })
        }
    }

    constructor(props) {
        super(props)

        this.state = {
            IRRBalance: 0,
            BTCBalance: 0,
            openBuyOffers: [],
            openSellOffers: [],
            closedBuyOffers: [],
            closedSellOffers: []
        }
    }

如你所见,我使用了 alert() 来显示状态值。这是我得到未定义的点,而不是API响应的确切值。

我怎么能解决它?

欣赏。

javascript react-native jsx
1个回答
1
投票

基本上setState()是异步工作的。所以你需要等待几纳秒才能得到值。你可以通过2种方式来实现。

1. 使用 await

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. 使用SetTimeOut **

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]
    })
  }
}
热门问题
推荐问题
最新问题