ReactJS:在设置父状态之前更新子组件

时间:2015-06-02 17:04:18

标签: reactjs reactjs-flux react-jsx

我有父子组件,子组件的状态(openWhen本质上是一个shouldChildRender)由父组件控制。在调用父级的setState()之后更新父状态之前,我遇到了更新子节点(接收道具)的问题,因此子节点接收到陈旧状态,直到第二次通过此流程。在第二次通过子进程时,接收更新状态并正确呈现。

父:

openDeactivateWarning: function (resource) {
    this.setState({
        openDeactivateModal: true,
        workingResource: resource
    });

    console.log('this.state.openDeactivateModal is still false here', this.state);
},

render: function () {
    return (
        <Modal openWhen={this.state.openDeactivateModal} openCallback={this.openDeactivateWarning}>
            <p>Some Modal content</p>
        </Modal>
    )
}

子:

componentWillReceiveProps: function () {
    console.log('This is fired before parent state changes and openModal is not called');

    if (this.props.openWhen) {
        this.openModal();
    }
},

我知道setState()不会立即导致状态改变,但我的印象是在实际更改状态后仍会重新呈现子项。有更好的方法来实现这个目标吗?

1 个答案:

答案 0 :(得分:4)

你应该使用更新的nextProps。当父组件更新其状态时,this.props.openWhen中的componentWillReceiveProps仍然是旧的。{/ p>

componentWillReceiveProps: function (nextProps) {
    console.log('This is fired before parent state changes and openModal is not called');

    if (nextProps.openWhen) { <-- updated props
        this.openModal();
    }
}
相关问题