反应状态未更新。

时间:2018-08-13 17:23:18

标签: reactjs react-native

我只是控制台日志记录,以查看我的状态是否正在更新,而且令人惊讶的是,我看到我的状态未更新。

这让我问,React中更新状态的正确方法是什么?

请考虑以下代码段

state = {
        increased: false,
        decreased: false
    }

现在,我想更新componentWillRecieveProps中的状态,所以我做了这样的事情

   componentWillReceiveProps(nextProps) {
    if (this.props.coinPrice != nextProps.coinPrice ) { 
       if (this.props.coinPrice > nextProps.coinPrice) {
         console.log("1")
          this.setState({decreased: true, increased: false})
          console.log(this.state) 
       }
       if (this.props.coinPrice < nextProps.coinPrice) {
        console.log("2")
        this.setState({increased: true, decreased: false})
        console.log(this.state)
       }
    }
}

在这里,第一个Console.log显示状态为

: Object {
22:35:35:   "decreased": false,
22:35:35:   "increased": false,
22:35:35: }

第二次更新状态。现在我的第一个问题是如何在此处使用传播算子更新状态?为什么console.log不会显示更新状态?

0 个答案:

没有答案
相关问题