更新组件中“脏”状态的最佳方法是什么?

时间:2018-02-14 23:35:31

标签: reactjs

如果我有一个反应组件会弹出一个“你确定”确认模式,如果状态是脏的,那么标记脏的最方便的方法是什么?我有一个基本的本地数组状态的对象,可以更改其值,并删除/添加项目。现在我在valuesChanged(),addItem(),deleteItem(),toggleSwitch()等中有一个setState({dirty:true})。我知道有一个不那么冗余的方法来完成这个,也许比较一个组件中的状态生命周期。我只是不确定该怎么做。

2 个答案:

答案 0 :(得分:0)

@justin,您可以使用/L生命周期方法:

componentWillReceiveProps

参考:https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class

答案 1 :(得分:0)

React 17.0将删除componentWillReceiveProps生命周期钩子(以及其他几个)并将在React 16.3中开始弃用过程。有关更多信息,请参阅this github issue。还有博客文章。

所以说,你可以做这样的事情:

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
}
相关问题