文章目錄
- 一文講清楚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實現服務端渲染