为什么子组件不以父级状态更新?

时间:2017-02-25 23:17:44

标签: reactjs

我将我的父状态传递给我的子组件,但是当我在子组件中打印道具时,我得到父组件的先前状态而不是最新状态。我很确定它是因为0是异步的。

this.setState

1 个答案:

答案 0 :(得分:4)

componentWillReceiveProps在组件更新呈现之前。 If you read the docs他们解释说你引用了下一个道具。

componentWillReceiveProps(nextProps, nextState){
    this.props.something // old value
    nextProps.something // new value
}

现在在渲染完成后进行了更新。

componentDidUpdate(previousProps){
    this.props.somehting // new value
    previousProps.something // old value
}

你的问题是你在新的道具打印出新的道具之前更新旧的道具。你需要的是componentDidUpdate或者看看下一个道具