【发布时间】:2018-11-13 20:26:01
【问题描述】:
所以我试图制作一个从服务器请求数据的组件,我希望能够在我将它提交到其他地方之前更改它,以前我会这样做 li
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}));
}
}
【问题讨论】:
-
getDerivedStateFromProps 在每个渲染方法之后调用 是的
getDerivedStateFromProps将在您更改状态或更改道具时调用。如果您想阻止在props更改时呈现,请使用shouldComponentUpdate
标签: reactjs