因此,我试图制作一个从服务器请求数据的组件,并且我希望能够在提交数据之前更改它,之前我会这样做的。
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}));
}
}发布于 2018-11-13 20:29:41
首先,在componentWillReceiveProps示例中,不应该直接设置状态。相反,您应该调用this.setState。
不过,要回答你的问题..。你为什么不选择在componentDidUpdate中这样做呢?这可能比使用getDerivedStateFromProps更好。
https://stackoverflow.com/questions/53288967
复制相似问题