在渲染与生命周期方法中对计算进行反应

Eva*_*van 2 javascript reactjs

我正在努力了解一些有关反应的内容,并希望了解更好的方法.

基本上,我想对传入的道具进行一些转换/计算.我目前基于事件的状态变化有限,但未来可能会发生变化.基本上,在渲染中进行这些计算,还是在componentWillMount和componentWillReceiveProps中设置状态更好?

在渲染示例中:

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>
}
Run Code Online (Sandbox Code Playgroud)

渲染之外:

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})
}
Run Code Online (Sandbox Code Playgroud)

我的想法是第二种方式更好,因为你不会在每次渲染时都进行计算,只有在事情发生变化时.有什么可以接受的方式呢?

Amb*_*oos 5

为了简单和可读性,您应该将它们保留在渲染中,并实现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.
}
Run Code Online (Sandbox Code Playgroud)

如果从false返回false shouldComponentUpdate,则不会再次调用render.如果this.props.data === nextProps.data你可能会返回false.

它避免了你保持不必要的状态,并且是可读的.如果你想使检查更精细,你可以分散你urlsomething成不同的组件,用自己的shouldComponentUpdate.

有关更多信息,请参阅https://facebook.github.io/react/docs/advanced-performance.html