介紹幾種方法可以加快你的React應(yīng)用秘车。
一.使用生產(chǎn)版本
默認(rèn)情況下州既,React包含很多在開發(fā)過程中很有幫助的警告。然而,這會導(dǎo)致React更大更慢乱顾。因此,在部署應(yīng)用時,確認(rèn)使用了生產(chǎn)版本。
最好在開發(fā)應(yīng)用時使用開發(fā)模式谭网,部署應(yīng)用時換為生產(chǎn)模式。
二. 避免重新渲染
可以通過重寫生命周期函數(shù) shouldComponentUpdate
來優(yōu)化性能赃春,這是在重新渲染過程開始之前觸發(fā)的愉择。該函數(shù)的默認(rèn)實(shí)現(xiàn)中返回的是true
,使得 React 執(zhí)行更新操作:
shouldComponentUpdate(nextProps, nextState) {
return true;
}
如果在某些情況下你的組件不需要更新织中,name你可以在shouldComponentUpdate
返回false
來跳過整個渲染過程锥涕,包括這個組件和后面調(diào)用的render()。
三. 使用shouldComponentUpdate
例子:
如果你想要你的組件僅當(dāng) props.color
或 state.count
發(fā)生改變時需要更新狭吼,你可以通過 shouldComponentUpdate
函數(shù)來檢查:
class CounterButton extends React.Component {
constructor(props) {
super(props);
this.state = {count: 1};
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state.count !== nextState.count) {
return true;
}
return false;
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>
Count: {this.state.count}
</button>
);
}
}
但是同時React提供了一個helper實(shí)現(xiàn)上面的邏輯层坠,繼承React.PureComponent。因此下面代碼是一種更簡單的方式實(shí)現(xiàn)了相同功能:
class CounterButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = {count: 1};
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>
Count: {this.state.count}
</button>
);
}
}
大多數(shù)情況下搏嗡,可以使用React.PureComponent,但是如果存在更復(fù)雜的數(shù)據(jù)結(jié)構(gòu)窿春,可能會出現(xiàn)問題拉一。例如當(dāng)你像一個list里添加(push)item的時候采盒,代碼是不會執(zhí)行的。因?yàn)殡m然數(shù)組中的值發(fā)生了改變蔚润,但是新的list和舊的list的值是相同的磅氨,所以不會進(jìn)行更新。
不可變數(shù)據(jù)的力量
避免這類問題最簡單的方法是不要突變(mutate) props 或 state 的值嫡纠。上述添加item的方法可以通過使用 concat 重寫:
handleClick() {
this.setState(prevState => ({
words: prevState.words.concat(['marklar'])
}));
}
或者用ES6對于數(shù)組支持展開語法烦租,使得解決上述問題更加方便。
handleClick() {
this.setState(prevState => ({
words: [...prevState.words, 'marklar'],
}));
};