react优化--pureComponent

it2022-05-09  32

shouldComponentUpdate的默认渲染

在React Component的生命周期中,shouldComponentUpdate方法,默认返回true,也就意味着就算没有改变props或state,也会导致组件的重绘。React 会非常频繁的调用这个函数,所以要确保它的执行速度够快。如此一来,会导致组件因为不相关数据的改变导致重绘,极大的降低了React的渲染效率。比如

//Table Component{this.props.items.map(i =>  <Cell data={i} option={this.props.options[i]} />)}

重写shouldComponentUpdate任何options的变化都可能导致所有cell的重绘,此时我们可以重写cell的shouldComponentUpdate以此来避免这个问题class Cell extends React.Component {   shouldComponentUpdate(nextProps, nextState) {    if (this.props.option === nextProps.option) {      return false;    } else {      return true;    }  }}这样只有在关联option发生变化时进行重绘。

 但是PureComponent是使用浅比较==判断组件是否需要更新,

 比如 obj[i].age=18;obj.splice(0,1);等,都是在源对象上进行修改,地址不变,因此不会进行重绘。

解决此列问题,推荐使用immutable.js。

 immutable.js会在每次对原对象进行添加,删除,修改使返回新的对象实例。任何对数据的修改都会导致数据指针的变化。

 避免设置对象的默认值

{this.props.items.map(i =><Cell data={i} options={this.props.options || []} />)}若options为空,则会使用[]。[]每次会生成新的Array,因此导致Cell每次的props都不一样,导致需要重绘。解决方法如下: const default = [];{this.props.items.map(i =><Cell data={i} options={this.props.options || default} />)}内联函数函数也经常作为props传递,由于每次需要为内联函数创建一个新的实例,所以每次function都会指向不同的内存地址。比如:render() {<MyInput onChange={e => this.props.update(e.target.value)} />;}以及:update(e) { this.props.update(e.target.value);}render() { return <MyInput onChange={this.update.bind(this)} />;}注意第二个例子也会导致创建新的函数实例。为了解决这个问题,需要提前绑定this指针:constructor(props) { super(props); this.update = this.update.bind(this);}update(e) { this.props.update(e.target.value);}render() { return <MyInput onChange={this.update} />;}

转载于:https://www.cnblogs.com/fancyLee/p/8029458.html

相关资源:数据结构—成绩单生成器

最新回复(0)