Reactjs 更新组件内“脏”状态的最佳方法?
如果我有一个react组件,它会弹出一个确认模式。如果状态是脏的,那么最方便的标记脏的方法是什么?我有一个对象的基本本地数组状态,可以更改它们的值,并删除/添加项目。现在,我在valuesChanged、addItem、deleteItem、toggleSwitch等中有一个setState{dirty:true}。我知道有一种不太冗余的方法来实现这一点,可能是比较组件生命周期中的状态。我只是不知道怎么做 @justin,您可以使用componentWillReceiveProps生命周期方法:Reactjs 更新组件内“脏”状态的最佳方法?,reactjs,Reactjs,如果我有一个react组件,它会弹出一个确认模式。如果状态是脏的,那么最方便的标记脏的方法是什么?我有一个对象的基本本地数组状态,可以更改它们的值,并删除/添加项目。现在,我在valuesChanged、addItem、deleteItem、toggleSwitch等中有一个setState{dirty:true}。我知道有一种不太冗余的方法来实现这一点,可能是比较组件生命周期中的状态。我只是不知道怎么做 @justin,您可以使用componentWillReceiveProps生命周期方法:
componentWillReceiveProps(nextProps) {
if(nextProps.dirty !== this.props.dirty) {
***do something here****
}
}
参考资料:React 17.0将删除组件WillReceiveProps lifecycle hook和其他一些组件,并将在React 16.3中开始弃用过程。有关更多信息,请参阅。也有一篇博客文章 这么说,你可以这样做:
componentDidUpdate(prevProps, prevState) {
//add whatever comparison logic you need here
if(this.state.someValue !== prevState.someValue && !this.state.dirty) {
this.setState({ dirty: true });
}
//optionally you could also reset dirty here if you also
//persisted the original values and the user undid their
//changes
}
不过,我希望能够在这个生命周期中将状态标记为dirty,并且输入更改不会触发组件swillreceiveprops。