11-10-react性能优化

PureRenderMixin 优化

PureRenderMixin 优化

react最常用的工具就是PureRenderMixin,使用 npm i react-addons-pure-render-mixin --save,安装并使用:

import React,{Component} from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'

class Demo extends Component{
    constructor(props, context) {
        super(props, context);
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
    }
    //省略其他代码....
}

eact的生命周期hook中有个shouldComponentUpdate,组件每一次改动,都要问一下这个函数是否要执行更新,当这个函数返回true,则执行更新。返回false,则不执行更新。默认的情况下,这个函数一直会返回true,即一些无效的更新也会执行。

为什么会有无效的改动?我们都知道,在react组件中,state和props的改变都会触发组件的更新和重新渲染。但是在react中有些时候state和props没有改变也会触发更新。这样就会导致无效的渲染。

这里使用this.shouldComponentUpdate=PureRenderMixin.shouldComponentUpdate.bind(this),实际上是对组件原来的shouldComponentUpdate的方法进行重写,每次更新之前都要查看props和state的是否发生改变,如果改变;就返回false,没有就返回true。

所以我们在react开发中都尽量在组件中加入PureRenderMixin方法去优化性能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值