zoukankan      html  css  js  c++  java
  • react优化--pureComponent

    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} />;
    }
    一点一滴累积,总有一天你也会成为别人口中的大牛!
  • 相关阅读:
    批量替换文本的工具
    wcf异常显示错误到客户端
    文件以二进制存入数据库和从数据库读取二进制文件
    关于关系数据库的范式
    对于挑战书上的很久之前都看不懂的DP看懂的突破
    操作系统概念
    关于P,V操作理解的突破,关于并发设计与并行
    关于快速沃尔什变换
    我觉得我应该养成经常翻收藏夹的习惯
    目前我的思考模式
  • 原文地址:https://www.cnblogs.com/fancyLee/p/8029458.html
Copyright © 2011-2022 走看看