关于react性能优化,在react 16这个版本,官方推出fiber,在框架层面优化了react性能上面的问题。因为这个太过于庞大,咱们今天围绕子自组件更新策略,从两个及其微小的方面来谈react性能优化。 其主要目的就是防止没必要要的子组件渲染更新。css
首先咱们看个例子,父组件以下: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用于管理子组件状态。两个点击事件用于分别修改两个状态redux
子组件写法以下:数组
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:ide
shouldComponentUpdate(nextProps,nextState){
console.log('当前现有的props值为'+ this.props.sonMsg); console.log('即将传入的props值为'+ nextProps.sonMsg); return this.props.sonMsg !== nextProps.sonMsg }
这样就解决了没必要要的更新。函数
在上述例子中,咱们看到了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一直没有变化。若是是非全局变量,或没被引用,就会被系统垃圾回收。
React.PureComponent 中的 shouldComponentUpdate() 仅做对象的浅层比较。若是对象中包含复杂的数据结构,则有可能由于没法检查深层的差异,产生错误的比对结果。仅在你的 props 和 state 较为简单时,才使用 React.PureComponent,或者在深层数据结构发生变化时调用 forceUpdate() 来确保组件被正确地更新。你也能够考虑使用 immutable 对象加速嵌套数据的比较。
此外,React.PureComponent 中的 shouldComponentUpdate() 将跳过全部子组件树的 prop 更新。所以,请确保全部子组件也都是“纯”的组件。
上述咱们花了很大篇幅,讲的都是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);
注意点以下:
本次咱们讨论了react组件渲染的优化方法之一。class组件对应PureComponent,function组件对应memo。也简单讲述了在使用过程当中的注意点。后续开发组件的时候,或许能对性能方面有必定的提高。