1. 使用 PureComponent 或者 shouldComponentUpdate
PureComponent沒(méi)有狀態(tài),他們只是渲染組件基于數(shù)據(jù)通過(guò)道具。如果改變props 改變它只被重新呈現(xiàn)考传。shouldComponentUpdate生命周期方法用于常規(guī)的組件,通過(guò)返回false取消重新呈現(xiàn)某些場(chǎng)景
- 以下兩個(gè)場(chǎng)景
class MyComponent extends PureComponent {
//
}
class MyComponent extends Component {
//
shouldComponentUpdate(nextProps, nextState) {
if(this.props.firstProp === nextProps. firstProp &&
this.props.secondProp === nextProps.secondProp) {
return false;
}
return true
}
//
}
上面的兩個(gè)例子可以幫助節(jié)省一些浪費(fèi)的呈現(xiàn)敬锐。第一個(gè)例子已經(jīng)實(shí)施shouldComponentUpdate邏輯告唆。第二個(gè)例子可以有更多的控制蛋叼《榧ǎ可以在組件維護(hù)狀態(tài)和停止重新呈現(xiàn)如果狀態(tài)沒(méi)有改變
- 比如 控制是否顯示加載中
class MyComponent extends Component {
shouldComponentUpdate(nextProps, nextState) {
if(this.state.isLoading === nextState. isLoading) {
return false;
}
return true
}
}
2. 在List 中使用 key attribute
列表是任何應(yīng)用程序中最常用的東西俊啼。如果你不為每個(gè)列表項(xiàng),當(dāng)任何一項(xiàng)從列表中添加或刪除時(shí)肺缕,會(huì)重新render每一項(xiàng)。擁有一個(gè)唯一鍵在每個(gè)列表項(xiàng),只重新呈現(xiàn)一遍授帕。
class MyComponent extends PureComponent {
render() {
return this.props.data.map((item, i) => {
return <Text key={item.id}>{item.title}</Text>
});
}
}
3.早點(diǎn)綁定方法 不要在render里面創(chuàng)建方法
- Do This
class MyComponent extends PureComponent {
constructor(props) {
super(props);
//do this
this.doWork = this.doWork.bind(this);
}
doWork() {
// doing some work here.
// this.props.dispatch....
}
render() {
return <Text onPress={this.doWork}>Do Some Work</Text>
}
}
- Don't This
<Text onPress={ () => this.doWork() }>Do Some Work</Text>
- 或者
<Text onPress={ this.doWork.bind(this) }>Do Some Work</Text>
因?yàn)閞ender經(jīng)常被渲染,每次渲染一次,創(chuàng)建一個(gè)新的函數(shù)搓谆。所以提前綁定函數(shù)。只創(chuàng)建一次豪墅。如果想向doWork函數(shù)傳遞參數(shù),可以使用以下方式
doWork = (param) => {
console.log(param)
}
<Text onPress={this.doWork(someVarParam)}Do Some Work With Args</Text>
4.Don’t update state or dispatch actions in componentWillUpdate
componentWillUpdate生命周期方法用于準(zhǔn)備更新,不會(huì)觸發(fā)另一個(gè)泉手。如果你想設(shè)置狀態(tài)或派遣任何回來(lái)的行動(dòng),他們?cè)赗eactV16.3版本后被componentWillReceiveProps代替。
5.使用性能監(jiān)視器看FPS
開(kāi)啟開(kāi)發(fā)工具性能監(jiān)視器偶器。當(dāng)你開(kāi)始互動(dòng),導(dǎo)航或滾動(dòng)你的應(yīng)用程序,可能會(huì)看到有時(shí)FPS變化很大,主要是其在JS線程,而不是本地UI線程上斩萌。
所以開(kāi)始尋找痛點(diǎn),你可能設(shè)置狀態(tài)或派遣回來(lái)的行動(dòng)在錯(cuò)誤的地方∑梁洌或做太多的JS線程同步工作颊郎,進(jìn)而優(yōu)化性能。