2015-12-08 38 views
0

我來自一個Ember背景,它計算了延遲計算的屬性,然後緩存直到依賴屬性發生變化。在反應組件中緩存方法的值

說我有以下設置在反應:

export default React.createClass({ 
    getInitialState: function(){ 
     return { 
      firstName: 'John', 
      lastName: 'Smith' 
     } 
    }, 

    fullName: function(){ 
     console.log('full name is computed') 
     return `${this.state.firstName} ${this.state.lastName}`; 
    }, 

    changeFirstName: function(){ 
     this.setState({ firstName: 'somethingElse'}); 
    }, 

    changeUnrelatedState: function(){ 
     this.setState({ blah: 'zzzzzz' }); 
    }, 

    render: function(){ 
     return (
      <div>{this.state.firstName} and {this.state.lastName} makes {this.fullName()}</div> 

      <button onClick={this.changeFirstName}>Change first name</button 
      <button onClick={this.changeUnrelatedState}>Change some state variable</button 
     ); 
    } 
}); 

當我點擊「更改一些狀態變量」按鈕,該組件重新呈現和fullName方法重新計算。這是一個簡單的例子,但是如果fullName方法執行了昂貴的計算呢?無論firstNamelastName是否更改,但每次狀態更改時都會運行,但仍會觸發該昂貴的操作。

是否存在緩存方法值的反應方式,而不是在每個渲染過程中重新計算它?

回答

2

通過將我們昂貴的計算提取到新組件中,我們可以實現shouldComponentUpdate,並且只在需要時重新計算。這樣我們就可以「緩存」已經計算過的值。

var FullNameComponent = React.createClass({ 
    shouldComponentUpdate: function (nextProps, nextState) { 
     //Props was the same no need for re-rendering 
     if (nextProps.firstName === this.props.firstName) return false; 

     //Props has changed, recalculate! 
     return true; 
    }, 
    performExpensiveCalculation: function() { 
     console.log('rerenders'); 
     return `${this.props.firstName} ${this.props.lastName}`; 
    }, 
    render: function() { 
     return (<div>{this.performExpensiveCalculation()}</div>); 
    } 
});