简体   繁体   中英

React - capture intermediate in shouldComponentUpdate

I need to do a non-trivial computation as part of my implementation of shouldComponentUpdate . I also need to do the same computation as part of the render implementation. I'd like to be able to capture the result of the computation in shouldComponentUpdate and reuse it in my render implementation - ie I'd like to avoid computing the same value twice.

Is there a recommended way to implement this?

The best way to do this is probably to define your own setState() wrapper inside your component like:

setMyState(newProps, newState) {
  var nonTrivialResult = doStuff(newProps, newState);
  newState.checkSum = nonTrivialResult;
  this.setState(newState);
}

And call this new method wherever you would call setState() , and also from componentWillReceiveProps .

The wrapper has access to all current props and state as well as any new props and state you pass in. That way, you should be able to do any calculation you want.

Also, you may need to call doStuff() from getInitialState() for the first round.

In this setup, your computation is done only once on every render. And you can check the result in shouldComponentUpdate() .

In the react lifecycle, shouldComponentUpdate() is called after componentWillReceiveProps() , so this should work..

Can you handle it at componentWillReceiveProps and update the state there with the computed result? (sorry this should be more like a comment but I don't have enough rep)

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