前言

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

子组件何时更新?

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

import React,{Component} from 'react';
import ComponentSon from './components/ComponentSon';
import './App.css'; class App extends Component{ state = {
parentMsg:'parent',
sonMsg:'son'
}
render(){
return (
<div className="App">
<header className="App-header" onClick={()=> {this.setState({parentMsg:'parent' + Date.now()})}}>
<p>
{this.state.parentMsg}
</p>
</header>
<ComponentSon sonMsg={this.state.sonMsg}/>
</div>
);}
} export default App;

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

子组件写法如下:

import React,{Component} from 'react';
export default class ComponentSon extends Component{
render(){
console.log('Component rendered : ' + Date.now());
const msg = this.props.sonMsg;
return (
<div> {msg}</div>
)
}
}

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

PureComponent rendered : 1561790880451

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

// shouldComponentUpdate
import React,{Component} from 'react';
export default class ComponentSon extends Component{
shouldComponentUpdate(nextProps,nextState){
console.log('当前现有的props值为'+ this.props.sonMsg);
console.log('即将传入的props值为'+ nextProps.sonMsg);
}
render(){
console.log('PureComponent rendered : ' + Date.now());
const msg = this.props.sonMsg;
return (
<div> {msg}</div>
)
}
}

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

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

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

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

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

PureComponent 更新原理(class 组件)

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

import React,{PureComponent} from 'react';
export default class ComponentSon extends PureComponent{
render(){
console.log('PureComponent rendered : ' + Date.now());
const msg = this.props.sonMsg;
return (
<div> {msg}</div>
)
}
}

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

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

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

import React,{Component} from 'react';
import ComponentSon from './components/ComponentSon';
import './App.css'; class App extends Component{ state = {
parentMsg:'parent',
sonMsg:{
val:'this is val of son'
}
}
render(){
return (
<div className="App">
<header className="App-header" onClick={()=> {this.setState({parentMsg:'parent' + Date.now()})}}>
<p>
{this.state.parentMsg}
</p>
</header>
<button onClick={()=>
this.setState(({sonMsg}) =>
{
sonMsg.val = 'son' + Date.now();
console.table(sonMsg);
return {sonMsg}
})
}>修改子组件props</button>
<ComponentSon sonMsg={this.state.sonMsg}/>
</div>
);}
} export default App;

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

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

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

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

this.setState(({sonMsg}) =>
{
sonMsg.val = 'son' + Date.now();
console.table(sonMsg);
return {sonMsg}
})

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

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

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

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

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

         this.setState(({sonMsg}) =>
{
console.table(sonMsg);
return {
sonMsg:{
...sonMsg,
val:'son' + Date.now()
} }
})

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

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

let str = "abc"; // str 不能改变了。
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 将跳过渲染组件的操作并直接复用最近一次渲染的结果。

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

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

import React,{memo} from 'react';

 const MemoSon =  memo(function Son(props){
console.log('MemoSon rendered : ' + Date.now());
return (
<div>{props.val}</div>
)
})
export default MemoSon;

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

function MyComponent(props) {
/* 使用 props 渲染 */
}
function areEqual(prevProps, nextProps) {
/*
如果把 nextProps 传入 render 方法的返回结果与
将 prevProps 传入 render 方法的返回结果一致则返回 true,
否则返回 false
*/
}
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. WPF去除边框的方法

    原文:WPF去除边框的方法 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/yangsen600/article/details/81978125 W ...

  2. TCP协议是如何保证可靠传输的【经典】

    参考:http://blog.csdn.net/cmm0401/article/details/77878998 从特点上我们已经知道,TCP 是可靠的但传输速度慢 ,UDP 是不可靠的但传输速度快. ...

  3. 贝叶斯推理(Bayes Reasoning)、独立与因式分解

    P(X,Y)=P(X)P(Y),X⊥Y P(X,Y,Z)∝ϕ1(X,Z)ϕ2(Y,Z),(X⊥Y∣∣Z) 1. Reasoning patterns causal reasoning 由原因到结果的一 ...

  4. springCloud跨域访问

    转自:http://blog.csdn.net/wangkang80/article/details/72829390 什么是跨域? 假设你在http://xxx.com/test/下有一个js文件, ...

  5. [C/C++]_[VS2010使用源代码UTF8中国字符串转码ANSI问题]

    场景: 1.思想vs设置源文件UTF8编码,的代码串中国出现在它必须是utf8编码.不幸的是没有,假设源代码出现在中国字符串,在内存公交码ANSI编码. Unicode(UTF8) 代码页(65001 ...

  6. 像职业选手样编码:地道Python

    Code Like a Pythonista: Idiomatic Python David Goodger goodger@python.org http://python.net/~goodger ...

  7. 零元学Expression Design 4 - Chapter 7 使用内建功能「Clone」来达成Path的影分身之术

    原文:零元学Expression Design 4 - Chapter 7 使用内建功能「Clone」来达成Path的影分身之术 本章所介绍的是便利且快速的内建工具Clone ? 本章所介绍的是便利且 ...

  8. C# NetCore使用AngleSharp爬取周公解梦数据

    这一章详细讲解编码过程 那么接下来就是码代码了,GO 新建NetCore WebApi项目 空的就可以 NuGet安装 Install-Package AngleSharp 或者界面安装 using. ...

  9. String转Color

    原文:String转Color 很硬性的转换,谁知道更好的忘不吝赐教啊. /// <summary> /// String To Color /// </summary> // ...

  10. This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed.

    Attempt to load Oracle client libraries threw BadImageFormatException. This problem will occur when ...