阅读 1043

最佳实践React性能优化

1: React.lazy和React.Suspense封装dynamic函数动态引入组件

1:基本使用

//使用方法
import React, {Component} from 'react';
import {dynamic} from './utils';

const LoadingHome = dynamic(() => import('./components/Home'));
const LoadingUser = dynamic(() => import('./components/User'));

class App extends Component {
    state = {
        showHome: false,
        showUser: false
    }
    toggle = (key) => {
        this.setState({
            [key]: !this.state[key]
        })
    }
    render() {
        let {showHome, showUser} = this.state
        return (
            <div>
                {showHome && <LoadingHome/>}
                {showUser && <LoadingUser/>}
                <button onClick={() => this.toggle('showHome')}>showHome</button>
                <button onClick={() => this.toggle('showUser')}>showUser</button>
            </div>
        );
    }
}
export default App;
复制代码
//封装dynamic函数
import React from 'react';
const Loading = () => <div>Loading</div>;

export function dynamic(loadComponent) {
    const LazyComponent = React.lazy(loadComponent)
    return () => (
        <React.Suspense fallback={<Loading />}>
            <LazyComponent />
        </React.Suspense>
    )
}

复制代码

2:lazy原理剖析

function lazy(load) {
    return class extends React.Component {
        state = { Component: null }
        componentDidMount() {
            load().then(result => {
                this.setState({ Component: result.default});
            });
        }
        render() {
            let { Component } = this.state;
            return Component && <Component />;
        }
    }
}
复制代码

2: PureComponent,memo解决无效渲染问题

1:PureComponent,memo基本使用

import React,{PureComponent,memo,Component} from 'react';
export default class App extends React.Component{
    constructor(props){
        super(props);
        this.state = {title:'计数器',number:0}
    }
    add = (amount)=>{
        this.setState({number:this.state.number+amount});
    }
    render(){
        console.log('App render');
        return (
            <div>
                <Counter number={this.state.number}/>
                <button onClick={()=>this.add(1)}>+1</button>
                <button onClick={()=>this.add(0)}>+0</button>
                <ClassTitle title={this.state.title}/>
                <FunctionTitle title={this.state.title}/>
            </div>
        )
    }
}
class Counter extends Component{
    render(){
        console.log('Counter render');
        return (
            <p>{this.props.number}</p>
        )
    }
}
class ClassTitle extends Component{
    render(){
        console.log('ClassTitle render');
        return (
            <p>{this.props.title}</p>
        )
    }
}
const FunctionTitle = function (props) {
    console.log('FunctionTitle render');
    return  <p>{props.title}</p>;
}
复制代码

从上面可以看出只要父组件setstate,子组件无论class组件还是函数式组件无论props是否改变都会进行渲染, 很显然这样是不合理的,所以react自带两个东西PureComponent(类组件),memo(函数组件)具体使用如下

import React,{PureComponent,memo,Component} from 'react';
export default class App extends React.Component{
    constructor(props){
        super(props);
        this.state = {title:'计数器',number:0}
    }
    add = (amount)=>{
        this.setState({number:this.state.number+amount});
    }
    render(){
        console.log('App render');
        return (
            <div>
                <Counter number={this.state.number}/>
                <button onClick={()=>this.add(1)}>+1</button>
                <button onClick={()=>this.add(0)}>+0</button>
                <ClassTitle title={this.state.title}/>
                <FunctionTitle title={this.state.title}/>
            </div>
        )
    }
}

class Counter extends PureComponent{
    render(){
        console.log('Counter render');
        return (
            <p>{this.props.number}</p>
        )
    }
}
class ClassTitle extends PureComponent{
    render(){
        console.log('ClassTitle render');
        return (
            <p>{this.props.title}</p>
        )
    }
}
const FunctionTitle = memo(props=>{
    console.log('FunctionTitle render');
    return  <p>{props.title}</p>;
});
复制代码

效果显著,这样的话无论class组件还是函数式组件 只要props不变化,组件就不会在渲染

2:来我们一起手动实现 PureComponent,memo

import React from 'react';
export class PureComponent extends React.Component{
   shouldComponentUpdate(nextProps,nextState){
       return !shallowEqual(this.props,nextProps)||!shallowEqual(this.state,nextState)
   }
}
export function memo(OldComponent){
   return class extends PureComponent{
     render(){
       return <OldComponent {...this.props}/>
     }
}
}
export function shallowEqual(obj1,obj2){
   if(obj1 === obj2)
       return true;
   if(typeof obj1 !== 'object' || obj1 ===null || typeof obj2 !== 'object' || obj2 ===null){
       return false;
   }    
   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]!== obj2[key]){
           return false;
       }
   }
   return true;
}
复制代码

是不是很有趣😄

文章分类
前端
文章标签