prevState in componentDidUpdate is the currentState?

随声附和 提交于 2019-12-04 05:07:42

In the added code, you are mutating a reference object by changing just a property on the object. This means that eventually nextProps and previousProps in essence refer to the same reference.

So it is no surprise that your componentDidUpdate didn't find a difference.

What you should do is create a new version of your object, and use that one to set the state, like:

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

or if you don't have the spread operator, something like

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

note that:

componentDidUpdate() will not be invoked if shouldComponentUpdate() returns false. 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);
    }
}

in some cases better use something like lodash isEqual method to deeply compare your state/props when you use shouldComponentUpdate:

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

if you have sophisticated props/state this will boost your performance as no wasteful rendering occurs

Thank you Icepickle for your comment, which solved the problem.

Instead of doing

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

I did

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

Thanks again.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!