前言

关于react性能优化,在react 16这个版本,官方推出fiber,在框架层面优化了react性能上面的问题。由于这个太过于庞大,我们今天围绕子自组件更新策略,从两个及其微小的方面来谈react性能优化。 其主要目的就是防止不必要的子组件渲染更新。

子组件何时更新?

首先我们看个例子,父组件如下:

  1. import React,{Component} from 'react';
  2. import ComponentSon from './components/ComponentSon';
  3. import './App.css';
  4. class App extends Component{
  5. state = {
  6. parentMsg:'parent',
  7. sonMsg:'son'
  8. }
  9. render(){
  10. return (
  11. <div className="App">
  12. <header className="App-header" onClick={()=> {this.setState({parentMsg:'parent' + Date.now()})}}>
  13. <p>
  14. {this.state.parentMsg}
  15. </p>
  16. </header>
  17. <ComponentSon sonMsg={this.state.sonMsg}/>
  18. </div>
  19. );}
  20. }
  21. export default App;

父亲组件作为容器组件,管理两个状态,一个parentMsg用于管理自身组件,一个sonMsg用于管理子组件状态。两个点击事件用于分别修改两个状态

子组件写法如下:

  1. import React,{Component} from 'react';
  2. export default class ComponentSon extends Component{
  3. render(){
  4. console.log('Component rendered : ' + Date.now());
  5. const msg = this.props.sonMsg;
  6. return (
  7. <div> {msg}</div>
  8. )
  9. }
  10. }

无论什么点击哪个事件,都会触发 ComponentSon 的渲染更新。 控制台也可以看到自组件打印出来的信息:

  1. PureComponent rendered : 1561790880451

但是这并不是我们想要的吧?按理来说,子组件需要用到的那个props更新了,才会重新渲染更新,这个才是我们想要的。还好React 的class组件类中的shouldComponentUpdate可以解决我们的问题。

  1. // shouldComponentUpdate
  2. import React,{Component} from 'react';
  3. export default class ComponentSon extends Component{
  4. shouldComponentUpdate(nextProps,nextState){
  5. console.log('当前现有的props值为'+ this.props.sonMsg);
  6. console.log('即将传入的props值为'+ nextProps.sonMsg);
  7. }
  8. render(){
  9. console.log('PureComponent rendered : ' + Date.now());
  10. const msg = this.props.sonMsg;
  11. return (
  12. <div> {msg}</div>
  13. )
  14. }
  15. }

注意,这个shouldComponentUpdate要返回一个boolean值的,这里我没有返回,看看控制台怎么显示?当我点击修改parentMsg的元素时:

  1. 当前现有的props值为son
  2. 即将传入的props值为son
  3. Warning: ComponentSon.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.

也就是说,控制台给出了一个警告,同时shouldComponentUpdate默认返回true,即要更新子组件。因此,避免props没有发生变化的时候更新,我们可以修改shouldComponentUpdate:

  1. shouldComponentUpdate(nextProps,nextState){
  2. console.log('当前现有的props值为'+ this.props.sonMsg);
  3. console.log('即将传入的props值为'+ nextProps.sonMsg);
  4. return this.props.sonMsg !== nextProps.sonMsg
  5. }

这样就解决了不必要的更新。

PureComponent 更新原理(class 组件)

在上述例子中,我们看到了shouldComponentUpdate在 class 组件上的积极作用,是不是每个class组件都得自己实现一个shouldComponentUpdate判断呢?react 官方推出的PureComponent就封装了这个,帮忙解决默认情况下子组件渲染策略的问题。

  1. import React,{PureComponent} from 'react';
  2. export default class ComponentSon extends PureComponent{
  3. render(){
  4. console.log('PureComponent rendered : ' + Date.now());
  5. const msg = this.props.sonMsg;
  6. return (
  7. <div> {msg}</div>
  8. )
  9. }
  10. }

当父组件修改跟子组件无关的状态时,再也不会触发自组件的更新了。

用PureComponent会不会有什么缺点呢?

这里我们是传入一个string字符串(基本数据类型)作为props传递给子组件。 这里我们是传入一个object对象(引用类型)作为props传递给子组件。

  1. import React,{Component} from 'react';
  2. import ComponentSon from './components/ComponentSon';
  3. import './App.css';
  4. class App extends Component{
  5. state = {
  6. parentMsg:'parent',
  7. sonMsg:{
  8. val:'this is val of son'
  9. }
  10. }
  11. render(){
  12. return (
  13. <div className="App">
  14. <header className="App-header" onClick={()=> {this.setState({parentMsg:'parent' + Date.now()})}}>
  15. <p>
  16. {this.state.parentMsg}
  17. </p>
  18. </header>
  19. <button onClick={()=>
  20. this.setState(({sonMsg}) =>
  21. {
  22. sonMsg.val = 'son' + Date.now();
  23. console.table(sonMsg);
  24. return {sonMsg}
  25. })
  26. }>修改子组件props</button>
  27. <ComponentSon sonMsg={this.state.sonMsg}/>
  28. </div>
  29. );}
  30. }
  31. export default App;

当我们点击button按钮的时候,触发了setState,修改了state,但是自组件却没有跟新。为什么呢?这是因为:

PureComponent 对状态的对比是浅比较的

PureComponent 对状态的对比是浅比较的

PureComponent 对状态的对比是浅比较的

  1. this.setState(({sonMsg}) =>
  2. {
  3. sonMsg.val = 'son' + Date.now();
  4. console.table(sonMsg);
  5. return {sonMsg}
  6. })

这个修改state的操作就是浅复制操作。什么意思呢?这就好比

  1. let obj1 = {
  2. val: son
  3. }
  4. obj2 = obj1;
  5. obj2.val = son + '1234'; // obj1 的val 也同时被修改。因为他们指向同一个地方引用
  6. obj1 === obj2;// true

也就是说,我们修改了新状态的state,也修改了老状态的state,两者指向同一个地方。PureComponent 发现你传入的props 和 此前的props 一样的,指向同一个引用。当然不会触发更新了。

那我们应该怎么做呢?react 和 redux中也一直强调,state是不可变的,不能直接修改当前状态,要返回一个新的修改后状态对象

因此,我们改成如下写法,就可以返回一个新的对象,新对象跟其他对象肯定是不想等的,所以浅比较就会发现有变化。自组件就会有渲染更新。

  1. this.setState(({sonMsg}) =>
  2. {
  3. console.table(sonMsg);
  4. return {
  5. sonMsg:{
  6. ...sonMsg,
  7. val:'son' + Date.now()
  8. }
  9. }
  10. })

除了上述写法外,我们可以使用Object.assign来实现。也可以使用外部的一些js库,比如Immutable.js等。

而此前的props是字符串字符串是不可变的(Immutable)。什么叫不可变呢?就是声明一个字符串并赋值后,字符串再也没法改变了(针对内存存储的地方)。

  1. let str = "abc"; // str 不能改变了。
  2. str +='def' // str = abcdef

看上去str 由最开始的 ‘abc’ 变为‘abcdef’变了,实际上是没有变。 str = ‘abc’的时候,在内存中开辟一块空间栈存储了abc,并将str指向这块内存区域。 然后执行 str +='def'这段代码的时候,又将结果abcdef存储到新开辟的栈内存中,再将str指向这里。因此原来的内存区域的abc一直没有变化。如果是非全局变量,或没被引用,就会被系统垃圾回收。

forceUpdate

React.PureComponent 中的 shouldComponentUpdate() 仅作对象的浅层比较。如果对象中包含复杂的数据结构,则有可能因为无法检查深层的差别,产生错误的比对结果。仅在你的 props 和 state 较为简单时,才使用 React.PureComponent,或者在深层数据结构发生变化时调用 forceUpdate() 来确保组件被正确地更新。你也可以考虑使用 immutable 对象加速嵌套数据的比较。

此外,React.PureComponent 中的 shouldComponentUpdate() 将跳过所有子组件树的 prop 更新。因此,请确保所有子组件也都是“纯”的组件。

memo

上述我们花了很大篇幅,讲的都是class组件,但是随着hooks出来后,更多的组件都会偏向于function 写法了。React 16.6.0推出的重要功能之一,就是React.memo。

React.memo 为高阶组件。它与 React.PureComponent 非常相似,但它适用于函数组件,但不适用于 class 组件。

如果你的函数组件在给定相同 props 的情况下渲染相同的结果,那么你可以通过将其包装在 React.memo 中调用,以此通过记忆组件渲染结果的方式来提高组件的性能表现。这意味着在这种情况下,React 将跳过渲染组件的操作并直接复用最近一次渲染的结果。

  1. // 子组件
  2. export default function Son(props){
  3. console.log('MemoSon rendered : ' + Date.now());
  4. return (
  5. <div>{props.val}</div>
  6. )
  7. }

上述跟class组件中没有继承PureComponent一样,只要是父组件状态更新的时候,子组件都会重新渲染。所以我们用memo来优化:

  1. import React,{memo} from 'react';
  2. const MemoSon = memo(function Son(props){
  3. console.log('MemoSon rendered : ' + Date.now());
  4. return (
  5. <div>{props.val}</div>
  6. )
  7. })
  8. export default MemoSon;

默认情况下其只会对复杂对象做浅层对比,如果你想要控制对比过程,那么请将自定义的比较函数通过第二个参数传入来实现。

  1. function MyComponent(props) {
  2. /* 使用 props 渲染 */
  3. }
  4. function areEqual(prevProps, nextProps) {
  5. /*
  6. 如果把 nextProps 传入 render 方法的返回结果与
  7. 将 prevProps 传入 render 方法的返回结果一致则返回 true,
  8. 否则返回 false
  9. */
  10. }
  11. export default React.memo(MyComponent, areEqual);

注意点如下:

  • 此方法仅作为性能优化的方式而存在。但请不要依赖它来“阻止”渲染,因为这会产生 bug。
  • 与 class 组件中 shouldComponentUpdate() 方法不同的是,如果 props 相等,areEqual 会返回 true;如果 props 不相等,则返回 false。这与 shouldComponentUpdate 方法的返回值相反。

结语

本次我们讨论了react组件渲染的优化方法之一。class组件对应PureComponent,function组件对应memo。也简单讲述了在使用过程中的注意点。后续开发组件的时候,或许能对性能方面有一定的提升。

React性能优化之PureComponent 和 memo使用分析的更多相关文章

  1. react性能优化

    前面的话 本文将详细介绍react性能优化 避免重复渲染 当一个组件的props或者state改变时,React通过比较新返回的元素和之前渲染的元素来决定是否有必要更新实际的DOM.当他们不相等时,R ...

  2. React性能优化记录(不定期更新)

    React性能优化记录(不定期更新) 1. 使用PureComponent代替Component 在新建组件的时候需要继承Component会用到以下代码 import React,{Componen ...

  3. 关于React性能优化

    这几天陆陆续续看了一些关于React性能优化的博客,大部分提到的都是React 15.3新加入的PureComponent ,通过使用这个类来减少React的重复渲染,从而提升页面的性能.使用过Rea ...

  4. React 性能优化 All In One

    React 性能优化 All In One Use CSS Variables instead of React Context https://epicreact.dev/css-variables ...

  5. React性能优化 PureComponent

    为什么使用? React15.3中新加了一个 PureComponent 类,顾名思义, pure 是纯的意思, PureComponent 也就是纯组件,取代其前身 PureRenderMixin  ...

  6. react性能优化要点

    1.减少render方法的调用 1.1继承React.PureComponent(会自动在内部使用shouldComponentUpdate方法对state或props进行浅比较.)或在继承自Reac ...

  7. React性能优化总结

    本文主要对在React应用中可以采用的一些性能优化方式做一下总结整理 前言 目的 目前在工作中,大量的项目都是使用react来进行开展的,了解掌握下react的性能优化对项目的体验和可维护性都有很大的 ...

  8. React性能优化,六个小技巧教你减少组件无效渲染

    壹 ❀ 引 在过去的一段时间,我一直围绕项目中体验不好或者无效渲染较为严重的组件做性能优化,多少积累了一些经验所以想着整理成一片文章,下图就是优化后的一个组件,可以对比优化前一次切换与优化后多次切换的 ...

  9. React性能优化总结(转)

    原文链接: https://segmentfault.com/a/1190000007811296?utm_source=tuicool&utm_medium=referral 初学者对Rea ...

随机推荐

  1. C#--动态操作DataTable

    C#动态操作DataTable(新增行.列.查询行.列等) 方法一:动态创建一个DataTable ,并为其添加数据 public void CreateTable()        {        ...

  2. Obtaining Directory Change Notifications(微软的例子,使用FindFirstChangeNotification,FindNextChangeNotification,FindCloseChangeNotification API函数)

    An application can monitor the contents of a directory and its subdirectories by using change notifi ...

  3. Store-exclusive instruction conflict resolution

    A data processing system includes a plurality of transaction masters (4, 6, 8, 10) each with an asso ...

  4. MyEclipse迅速

    MyEclipse迅速 1.详细例如以下图 2.提示原因 3.解决方案 版权声明:本文博主原创文章.博客,未经同意不得转载.

  5. 机器学习: DeepDreaming with TensorFlow (一)

    在TensorFlow 的官网上,有一个很有趣的教程,就是用 TensorFlow 以及训练好的深度卷积神经(GoogleNet)网络去生成一些有趣的pattern,通过这些pattern,可以更加深 ...

  6. OpenGL(二十一) glPolygonOffset设置深度偏移解决z-fighting闪烁问题

    开启深度测试后OpenGL就不会再去绘制模型被遮挡的部分,这样实现的显示画面更为真实,但是由于深度缓冲区精度的限制,对于深度相差非常小的情况(例如在同一平面上进行两次绘制),OpenGL就不能正确判定 ...

  7. theano 深度学习大全

    1. theano 的设计理念与性能分析 Theano: a CPU and GPU Math Expression Compiler 2. thenao 深度学习 Deep Learning Tut ...

  8. javascript-DOM学习

    javascript-DOM学习 DOM document(html) object modle document对象(DOM核心对象) dom能用来干什么? 对html元素的样式(颜色.大小.位置等 ...

  9. maven私服nexus安装

    maven私服nexus安装 1.nexus特性 1.1.nexus私服实际上是一个javaEE的web 系统 1.2.作用:用来管理一个公司所有的jar包,实现项目jar包的版本统一 1.3.jar ...

  10. TestNg依靠先进的采用强制的依赖,并依赖序列的------TestNg依赖于特定的解释(两)

    原创文章,版权所有所有,转载,归因:http://blog.csdn.net/wanghantong TestNg使用dependsOnGroups属性来进行依赖測试, 測试方法依赖于某个或某些方法, ...