简体   繁体   中英

React: Previous props are not correct in componentDidUpdate

The use-case is to define a callback prop and need to compare its value in componentDidUpdate and based on that do some action. But previous props in the componentDidUpdate are similar to the new props.

Here is a code sandbox link where it can be seen.

The reason the value in componentDidUpdate is same because you are calling a function from parent which returns you the state value and since the sstate value is updated by the time you call the function, it returns you the new value.

If however you copy the state value to a variable in render and then then use that inside your function, it will return you the old value since its then bound by closure ie you are using a variable from lexical scope of the function when its created and when the component re-renders a new function reference is created with the updated value of state in lexical scope

render() {
    const val = this.state.myCallback;
    return (
      <div className="App">
        <button onClick={this.updateCallback} type="button">
          UPDATE CALLBACK
        </button>
        <Child myCallback={() => val} />
      </div>
    );
  }

编辑表格值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM