2017-09-02 133 views
0

我在我的React组件中有一个数据存储监听器,并且在设置状态的回调中。基于新状态中的参数,然后决定是否渲染组件。设置为true的状态返回false

我下面的代码是实现这一点,但意想不到的结果:

shouldComponentUpdate() { 
    if (this.props.questionId == 4687760) { 
     console.log(!!this.state.didAnswersChange); 
    } 
    return !!this.state.didAnswersChange; 
} 

onQuestionStoreChange() { 
    let questionStoreData = this.questionStore.get(this.props.questionId); 
    if (questionStoreData) { 
     if (this.props.questionId == 4687760) { 
      console.log(questionStoreData.didAnswersChange || false); 
     } 
     this.setState({ 
      didAnswersChange: questionStoreData.didAnswersChange || false 
     }); 
    } 
} 

在第一console.log我得到true打印出来。然后对于一些shouldComponentUpdate()打印出false

任何人都可以帮我理解这可能吗?我已验证打印输出的true确实来自onQuestionStoreChange(),而打印输出的false来自shouldComponentUpdate()

回答

1

按照Doc shouldComponentUpdate(nextProps, nextState):

shouldComponentUpdate()被接收到的新的道具或状态时呈现之前被调用。

shouldComponentUpdate接收新的状态和道具作为参数,this.state将仅具有prev值,以检查新的状态值使用newState.key。

为什么会这样?

默认情况下,此方法返回true,为了检查我们是否想渲染状态/道具变化的组件,我们需要prev值和新值。这就是为什么this.state只有在这个方法中才会有prev值的原因。

写这样的:

shouldComponentUpdate(nextProps, nextState){ 
    console.log(nextState.didAnswersChange); 
}