2016-05-12 71 views
2

我試圖瞭解一些關於反應的內容,並希望能夠通過更好的方式獲得想法。渲染與生命週期方法中的反應計算

基本上,我想對傳入的道具做一些轉換/計算。目前我基於事件的狀態變化有限,但未來可能會發生變化。基本上,在渲染,componentWillMount和componentWillReceiveProps和set state中做這些計算會更好嗎?

在渲染例如:

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

我的想法是第二種方式是更好,因爲你不這樣做的計算上的每個渲染,只有當事情改變。接受的方式是什麼?

回答

4

只是爲了簡單性和可讀性,你應該讓他們在渲染,並實現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,渲染不會再次調用。如果this.props.data === nextProps.data你可能會返回false。

它避免你保持不必要的狀態,並且可讀。如果您希望更細緻地進行檢查,您可以將urlsomething分成不同的組件,並使用它們自己的shouldComponentUpdate

欲瞭解更多信息,請參閱https://facebook.github.io/react/docs/advanced-performance.html

+0

是的,它通常建議你不要把計算數據進入狀態,而是重新計算它的渲染。請參閱https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-shouldnt-go-in-state – Brandon

+0

另外,最好在'componentWillReceiveProps()'生命週期特定只有東西:你需要當前'this.props'以及下一個道具的東西,或者你需要根據新的道具更新狀態的東西。 – wintvelt

相關問題