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方法執行了昂貴的計算呢?無論firstName
或lastName
是否更改,但每次狀態更改時都會運行,但仍會觸發該昂貴的操作。
是否存在緩存方法值的反應方式,而不是在每個渲染過程中重新計算它?