一文讲清楚React性能优化
文章目录
- 一文讲清楚React性能优化
- 1. React性能优化概述
- 2. React性能优化
- 2.1 render优化
- 2.2 较少使用内联函数
- 2.3 使用React Fragments避免额外标记
- 2.4 使用Immutable
- 上代码
- 2.5 组件懒加载
- 2.6 服务端渲染
- 2.7 其他优化手段
一文讲清楚React性能优化
1. React性能优化概述
React通过引入VirtualDOM,再加上diff算法,让渲染性能得到了极大的提升,但是我们依然可以通过很多方法,将性能进一步的 提升
2. React性能优化
2.1 render优化
直接看这篇文章一文讲清楚React的render优化,包括shouldComponentUpdate、PureComponent和memo
2.2 较少使用内联函数
- 使用内联函数会导致每次render时都创建新的函数实例,造成一定的性能影响,我们应尽量在render外实例化函数,然后再render中绑定就行
// 使用内联函数
class App extends React.Component{render(){return(<div><button onClick={()=>{/* do something */}}></button></div>)}
}
// 是使用内敛函数
class App extends React.Component{handleClick=()=>{/* do something */}render(){return(<div><button onClick={this.handleClick}></button></div>)}
}
2.3 使用React Fragments避免额外标记
因为React要求我们每个组件具有唯一父标签,所以我们经常会在最外层嵌套一个div,但是这样会增加DOM消耗
如果我们只是为了满足规则,而不需要在最外层标签做人也业务处理,则可以使用<>React Fragments来代替div
class App extends from React.Component{render(){return(<><span>use React Fragments</span></>)}
}
2.4 使用Immutable
- 首先,Immutable是一个js库,他的作用是让我们在进行对象引用时,不用拷贝整个原对象,而是截取当前节点及父节点,其他节点实现共享,形成一种不可变的数据结构
- 她提供了主要想Map(主要处理对象),Set(主要处理Array)等来操作对象
- 用之前先安装 npm install immutable
- 我们用Map来举例,
- 主要用法
- Map(obj)
- set(name,value)
- get(name)
- toJS(转回普通对象)
-
上代码
import React, { Component } from 'react';
import {Map} from 'immutable'
class App extends Component {state={info:Map({name:"tom",age:20,hobbit:Map({likeone:"basketball",liketwo:"football"})})}render() {return (<div>App<button onClick={()=>{this.setState({info:this.state.info.set("name","newTom")})}}>修改</button>{this.state.info.get("name")}<Child hobbit={this.state.info.get("hobbit")} ></Child> </div>);}
}
class Child extends Component{shouldComponentUpdate(nextProps,nextState){//判断hobbit的值是否更新if(this.props.hobbit===nextProps.hobbit){return false;}return true;}render(){return(<div>Child</div>);}componentDidUpdate(){console.log("子组件更新了");}
}
export default App;
- 实现不必要的render渲染
2.5 组件懒加载
- 我们在使用webpack的时候都知道,webpack支持代码拆分的能力,打包不同的bundle,然后再需要的时候动态加载,而不是一次性全部加载,减少初始包的大小
- React使用Suspense和lazy组件实现代码的拆分,即懒加载
- 上代码
const lazyComponent=React.lazy(()=>import(/* component name */))
function App(props){<React.Suspense><lazyComponent></lazyComponent></React.Suspense>
}
2.6 服务端渲染
- 我们可以使用服务端渲染的方式,加速首屏加载
- 可以使用Node服务,调用React.renderToString
- 也可以直接使用next.js实现服务端渲染