使用getDerivedStateFromProps对道具进行状态说明

时间:2018-11-13 20:26:02

标签: reactjs

因此,我试图制作一个从服务器请求数据的组件,并且我希望能够在我之前将其提交到其他地方之前更改它

componentWillReceiveProps(nextProps) {
    if (nextProps.dwelling) {
        this.state.dwelling = nextProps.dwelling;
    }
    if (!nextProps.saving && this.props.saving) {
        this.props.history.push('/users');
    }
}
}

注意:成功保存后,第二个if也非常有用。

但是由于不赞成componentWillReceiveProps,所以我试图对getDerivedStateFromProps做同样的事情:

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.dwelling !== prevState.dwelling) {
        return {dwelling: nextProps.dwelling}
    }
    return null
}

问题是getDerivedStateFromProps在每个渲染方法之后被调用,并且与我的onChange处理函数混淆,是否可以替换componentWillReceiveProps?我看到了有关使用shouldComponentUpdate的帖子,但似乎不是使用该方法的预期方式。

编辑: componentDidUpadte完成了这项工作:

componentDidUpdate(prevProps) {
    if (this.props.dwelling !== prevProps.dwelling){
        this.setState(() => ({dwelling: this.props.dwelling}));
    }
}

1 个答案:

答案 0 :(得分:2)

首先,在您的componentWillReceiveProps示例中,您不应该直接设置状态。相反,您应该呼叫this.setState

但是,要回答您的问题...您为什么不选择在componentDidUpdate中这样做?这可能比使用getDerivedStateFromProps更好。