1. 使用 PureComponent 或者 shouldComponentUpdate
PureComponent没有状态,他们只是渲染组件基于数据通过道具。如果改变props 改变它只被重新呈现。shouldComponentUpdate生命周期方法用于常规的组件,通过返回false取消重新呈现某些场景
- 以下两个场景
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
}
//
}
上面的两个例子可以帮助节省一些浪费的呈现。第一个例子已经实施shouldComponentUpdate逻辑。第二个例子可以有更多的控制。可以在组件维护状态和停止重新呈现如果状态没有改变
- 比如 控制是否显示加载中
class MyComponent extends Component {
shouldComponentUpdate(nextProps, nextState) {
if(this.state.isLoading === nextState. isLoading) {
return false;
}
return true
}
}
2. 在List 中使用 key attribute
列表是任何应用程序中最常用的东西。如果你不为每个列表项,当任何一项从列表中添加或删除时,会重新render每一项。拥有一个唯一键在每个列表项,只重新呈现一遍。
class MyComponent extends PureComponent {
render() {
return this.props.data.map((item, i) => {
return <Text key={item.id}>{item.title}</Text>
});
}
}
3.早点绑定方法 不要在render里面创建方法
- 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>
因为render经常被渲染,每次渲染一次,创建一个新的函数。所以提前绑定函数。只创建一次。如果想向doWork函数传递参数,可以使用以下方式
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生命周期方法用于准备更新,不会触发另一个。如果你想设置状态或派遣任何回来的行动,他们在ReactV16.3版本后被componentWillReceiveProps代替。
5.使用性能监视器看FPS
开启开发工具性能监视器。当你开始互动,导航或滚动你的应用程序,可能会看到有时FPS变化很大,主要是其在JS线程,而不是本地UI线程上。
所以开始寻找痛点,你可能设置状态或派遣回来的行动在错误的地方。或做太多的JS线程同步工作,进而优化性能。
网友评论