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} />;
    }
    一点一滴累积,总有一天你也会成为别人口中的大牛!
  • 相关阅读:
    可变性编程 不可变性编程 可变性变量 不可变性变量 并发编程 命令式编程 函数式编程
    hashable
    优先采用面向表达式编程
    内存转储文件 Memory.dmp
    windows update 文件 路径
    tmp
    查询局域网内全部电脑IP和mac地址等信息
    iptraf 网卡 ip 端口 监控 netstat 关闭端口方法
    Error 99 connecting to 192.168.3.212:6379. Cannot assign requested address
    t
  • 原文地址:https://www.cnblogs.com/fancyLee/p/8029458.html
Copyright © 2011-2022 走看看