简体   繁体   中英

React calculations in render vs in lifecycle methods

I'm trying to understand something about react and would like to get thoughts on the better way to do it.

Basically, I want to do some transformations/calculations on incoming props. I have limited event based state changes currently, but that may change in the future. Basically, is it better to do these calculations in render, or in componentWillMount and componentWillReceiveProps and set state?

in render example:

render() {
  var url = this.getUrl() // get url transforms some props into a valid url
  var something = this.getSomething() // etc etc

  return <a href={url}>{something}</a>
}

outside of render:

componentWillMount() {
  this._checkAndSetUrl(this.getUrl(this.props.data));
},
componentWillReceiveProps(nextProps) {
  const currentGivenUrl = this._getUrl(this.props.data)
  const nextGivenUrl = this._getUrl(nextProps.data)

  if (currentGivenUrl !== nextGivenUrl) {
    this._checkAndSetUrl(nextGivenUrl);
  }
},
_checkAndSetUrl(url) {
  // check validity and do some stuff to url
  url = "new url" 
  something = this.getSomething()

  this.setState({url: url, something: something})
}

My thinking is the second way is better because you don't do the calculations on every render, only when things are changed. What's the accepted way to do this?

Just for simplicity and readability you should keep them in render, and implement shouldComponentUpdate :

shouldComponentUpdate: function(nextProps, nextState) {
  // TODO: return whether or not current chat thread is
  // different to former one. this.props refers to the 'old' props.
}

If you return false from shouldComponentUpdate , render will not be called again. If this.props.data === nextProps.data you can probably return false.

It avoids you keeping around unnecessary state, and is readable. If you want to make the checks more granular you can split up your url and something into different components, with their own shouldComponentUpdate .

For more information, see https://facebook.github.io/react/docs/advanced-performance.html

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