React 组件更新优化

shouldComponentUpdateReact.PureComponent是类组件中的优化方式,而React.memo是函数组件中的优化方式。

1. PureComponent

  • PureComponent 通过 propstate浅比较来实现 shouldComponentUpdate,当 propstate 的值或者引用地址发生改变时,组件就会发生更新。
  • Component 只要 state 发生改变, 不论值是否与之前的相等,都会触发更新。
class ComponentDiffPure extends PureComponent {
  constructor() {
    super();
    this.state = { text: 'true' };
  }

  changeState = () => {
    this.setState({ text: 'false' });
  };

  render() {
    console.log('pure-render');
    return (
      <div>
        <button onClick={this.changeState}>Click</button>
        <div>{this.state.text}</div>
      </div>
    );
  }
}

2. shouldComponentUpdate

  • React提供了生命周期函数shouldComponentUpdate(),根据它的返回值(true | false),判断 React 组件是否更新
  • shouldComponentUpdate方法接收两个参数nextPropsnextState
  • 一般我们在 shouldComponentUpdate 中进行更深层次的更新控制
shouldComponentUpdate (nextProps, nextState) {
  return true
}

2.1 forceUpdate

  • 当明确知道父组件Parent修改了引用类型的数据(子组件的渲染依赖于这个数据)
  • 此时调用forceUpdate()方法强制更新子组件,
  • 注意,forceUpdate()会跳过子组件的shouldComponentUpdate()
  • 不推荐使用

2.2 immutable

  • Immutable 则提供了简洁高效的判断数据是否变化的方法,只需 ===is 比较就能知道是否需要执行 render()
  • Immutable.js是 Facebook 在 2014 年出的持久性数据结构的库,持久性指的是数据一旦创建,就不能再被更改,任何修改或添加删除操作都会返回一个新的 Immutable 对象
import { is } from 'immutable'

shouldComponentUpdate (nextProps = {}, nextState = {}) => {
  return !(this.props === nextProps || is(this.props, nextProps)) ||
      !(this.state === nextState || is(this.state, nextState))
}

3. React.memo

React.memo() 文档地址:https://reactjs.org/docs/react-api.html#reactmemo

  • 在函数组件中, React 提供了React.memo这个 HOC(高阶组件)
  • React.memo()可以支持指定一个参数
  • React.memo 仅检查 props 变更。如果函数组件被 React.memo 包裹,且其实现中拥有 useStateuseContext 的 Hook,当 context 发生变化时,它仍会重新渲染。
function MyComponent(props) {
  /* render using props */
}
function areEqual(prevProps, nextProps) {
  /*
  return true if passing nextProps to render would return
  the same result as passing prevProps to render,
  otherwise return false
  */
}
export default React.memo(MyComponent, areEqual);

使用方式很简单,在函数组件之外,在声明一个 areEqual 方法来判断两次 props 有什么不同,如果第二个参数不传递,则默认只会进行 props 的浅比较。

最终 export 的组件,就是 React.memo() 包装之后的组件

4. useMemo

  • useMemo() 进行细粒度性能优化
  • 在某些场景下,希望函数组件的一部分不要进行 re-render,而不是整个函数组件不要 re-render,也就是要实现局部Pure 功能。
  • 使用useMemo对依赖属性进行包装
// 根据count变化才会重新返回新的userInfo 
const userInfo = useMemo(() => {
  return {
    age: count,
    name: 'hello',
  };
}, [count]);

  return (
    <div>
      {number}-{count}
      <button onClick={btnHandler}>按钮</button>
      <ChildMemo userInfo={userInfo}/>
    </div>
  )
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值