componentDidUpdate中的prevState是currentState吗?

问题描述 投票:3回答:3

我过去使用过componentDidUpdate(),它已按预期工作。

然而,这一次,我做到了

componentDidUpdate(prevProps, prevState) {
    if (prevState.object.someString !== this.state.object.someString) {
        console.log(true);
    }
}

true从未登录。我将两个状态对象记录到控制台,发现它们完全相同:当前状态。

这是一个错误吗?我在这里错过了什么?

谢谢。

编辑:我试图用componentWillUpdate(nextProps, nextState)做同样的事情,再次,他们是同一个对象。

编辑2:我正在改变状态:

modifyObject = (field, value) => {
    const { object } = this.state;
    object[field] = value;
    this.setState({ object });
}
reactjs react-native state
3个回答
8
投票

在添加的代码中,您通过仅更改对象上的属性来改变引用对象。这意味着最终nextPropspreviousProps在本质上指的是相同的参考。

因此,你的componentDidUpdate没有发现差异就不足为奇了。

你应该做的是创建一个新版本的对象,并使用它来设置状态,如:

this.setState({ object: { ...object, [field]: value } })

或者,如果你没有传播运营商,那就像

this.setState( { object: Object.assign({}, object, { [field]: value }) } );

1
投票

注意:

如果shouldComponentUpdate()返回false,则不会调用componentDidUpdate()。 ref:https://reactjs.org/docs/react-component.html#componentdidupdate

 shouldComponentUpdate(nextProps, nextState) {
    if (this.state.someString !== nextState.someString) {
      return true;
    }
    return false;
  }

componentDidUpdate(prevProps, prevState) {
    if (prevState.someString !== this.state.someString) {
        console.log(true);
    }
}

在某些情况下,当你使用shouldComponentUpdate时,更好地使用像lodash isEqual方法来深入比较你的状态/道具:

shouldComponentUpdate(nextProps, nextState) {
        return !isEqual(this.state, nextState);
      }

如果你有复杂的道具/状态,这将提高你的表现,因为没有浪费的渲染发生


0
投票

谢谢Icepickle的评论,这解决了这个问题。

而不是做

modifyObject = (field, value) => {
    const { object } = this.state;
    object[field] = value;
    this.setState({ object });
}

我做到了

modifyObject = (field, value) => {
    const { object } = this.state;
    this.setState({ object: { ...object, [field]: value } });
}

再次感谢。

© www.soinside.com 2019 - 2024. All rights reserved.