react性能优化

208 阅读1分钟

react性能优化

路由懒加载

import {dynamic} from './utils'
const LazyHome = dynamic(()=>import(/*webpackPrefetch:true*/'./components/Home'))
<HashRouter>
    <Route path = '/' Component={LazyHome} />
<HashRouter>
utils.js
export function dynamic(LoadComponent){
    const LazyComponent = React.lazy(loadComponent)
    return ()=>(
        <React.Suspense fallback={<Loading>}>
            <LazyComponent/>
        <React.Suspense>
    )
}

自定义实现lazy

function lazy(loadComponent){
    return class extends React.Component{
        state = {Component: null}
        componentDidMount(){
            loadComponent().then(result=>{
                this.setState({Component: result.default})
            })
        }
        render(){
            const {Component} = this.state
            return Component&&<Component>
        }
    }
}

更新阶段的优化

API优化方法
  1. shouldComponentUpdate
  2. PureComponent 用于类组件,只要属性不更新就不重新渲染
  3. React.memo 用于函数组件,同PureComponent cosnt memoComp = React.memo(Comp)
  4. immutable
PureComponent和React.memo的代码实现
  1. PureComponent的实现
export class PureComponent extends React.Component{
    shouldComponnetUpdate(nextProps,nextState){
        return !shallowEqual(this.props,nextProps)||!shallowEaqual(this.state.nextState)
    }
}
function shallowEaqual(obj1,obj2){
    if(obj1===obj2){
        return true
    }
    let keys1 = Object.keys(obj1)
    let keys2 = Object.keys(obj2)
    if(keys1.length!=keys2.length){
        return false
    }
    for(let key of keys1){
        if(!obj2.hasOwnProperty(key)||obj1[key] !== obj1[key]){
            return false
        }
    }
}