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

时间:2016-05-12 15:37:38

标签: 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>
}

在渲染之外:

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})
}

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

1 个答案:

答案 0 :(得分: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.
}

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

它避免了你保持不必要的状态,并且是可读的。如果您想更仔细地进行检查,可以将urlsomething拆分为不同的组件,并使用自己的shouldComponentUpdate

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