什麼是存儲從React道具的昂貴計算結果的最佳位置,我在render()
中使用了這些道具,但不想在每個render()
執行?在哪裏存儲從道具計算的值React
constructor(props) {
super(props)
const result = this.doExpensiveCalculation(props)
}
componentWillReceiveProps(nextProps) {
// if nextProps differ from props
const result = this.doExpensiveCalculation(nextProps)
}
doExpensiveCalculation(props) {
// Some expensive stuff
}
render(){
// Use doExpensiveCalculation(this.props) here
}
選項是this
和state
但兩個我看到而未能如願。有沒有現成的解決方案,使用memoisation?
另一方面,我應該擔心優化嗎?我讀過React可以重新渲染組件,即使道具沒有改變但是這經常發生嗎?
您應該保存'狀態result'。如果可能的話'doExpensiveCalculation'應該以異步方式完成。如果你正在使用像redux和redux-saga這樣的東西,這應該很簡單。 – wesley6j