• 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} />;
    }
    一点一滴累积,总有一天你也会成为别人口中的大牛!
  • 相关阅读:
    DOCTYPE声明
    JS获取对象宽度和高度
    在Flash中巧妙替换字体
    web.config 配置兼容 IIS7 II6
    防刷新重复提交/防后退方法
    iframe自适应,跨域,JS的document.domain
    JS动态创建Table IE不显示Fix
    C#简繁转换
    用TransactSQL 命令压缩数据库
    JS内置对象[转载]
  • 原文地址:https://www.cnblogs.com/fancyLee/p/8029458.html
Copyright © 2020-2023  润新知