ReactJS:Child 组件在设置 parent 状态之前更新

ReactJS: Child component updates before parent state is set

我有 parent 和 child 组件,其中 child 的状态(openWhen 本质上是一个 shouldChildRender)由 parent.我 运行 遇到一个问题,在调用 parent 的 setState() 之后更新 parent 状态之前 child 被更新(接收道具)所以 child 收到陈旧状态,直到第二次通过此流。在第二次通过 child 接收更新的状态并正确呈现。

Parent:

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

Child:

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

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

我知道 setState() 不会立即导致状态更改,但我的印象是 children 在状态实际更改后仍会是 re-rendered。有没有更可取的方法来完成这个?

您应该使用已更新的 nextProps。 this.props.openWhen in componentWillReceiveProps 当父组件更新它的状态时仍然是旧的。

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

    if (nextProps.openWhen) { <-- updated props
        this.openModal();
    }
}