编写高性能React组件-传值篇

很多人在写React组件的时候没有太在意React组件的性能,使得React做了很多不必要的render,现在我就说说该怎么来编写搞性能的React组件。

首先我们来看一下下面两个组件

import React, {PureComponent,Component} from "react"
import PropTypes from "prop-types"
class A extends Component {
    constructor(props){
        super(props);
    }
    componentDidUpdate() {
        console.log("componentDidUpdate")
    }
    render (){
        return (
            <div />
        )
    }
}
class Test extends Component {
    constructor(props) {
        super(props);
        this.state={
            value:0
        };
    }
    static propTypes = {};
    static defaultProps = {};
    componentDidMount() {
        setTimeout(()=>{
            this.setState({value:this.state.value+1})
        },100);
    }
    render() {
        return (
            <A />
        )
    }
}

运行结果:

Test state change.
A componentDidUpdate

我们发现上面代码中只要执行了Test组件的中的setState,无论Test组件里面包含的子组件A是否需要这个state里面的值,A componentDidUpdate始终会输出

试想下如果子组件下面还有很多子组件,组件又嵌套子组件,子子孙孙无穷尽也,这是不是个很可怕的性能消耗?

当然,针对这样的一个问题最初的解决方案是通过shouldComponentUpdate方法做判断更新,我们来改写下组件A

class A extends Component {
    constructor(props){
        super(props);
    }
    static propTypes = {
        value:PropTypes.number
    };
    static defaultProps = {
        value:0
    };
    shouldComponentUpdate(nextProps, nextState) {
        return nextProps.value !== this.props.value;
    }
    componentDidUpdate() {
        console.log("A componentDidUpdate");
    }
    render (){
        return (
            <div />
        )
    }
}

这里增加了shouldComponentUpdate方法来对传入的value属性进行对面,虽然这里没有传,但是不影响,运行结果:

Test state change.

好了,这次结果就是我们所需要的了,但是如果每一个组件都这样做一次判断是否太过于麻烦?

那么React 15.3.1版本中增加了 PureComponent ,我们来改写一下A组件

class A extends PureComponent {
    constructor(props){
        super(props);
    }
    static propTypes = {
        value:PropTypes.number
    };
    static defaultProps = {
        value:0
    };
    componentDidUpdate() {
        console.log("A componentDidUpdate");
    }
    render (){
        return (
            <div />
        )
    }
}

这次我们去掉了shouldComponentUpdate,继承基类我们改成了PureComponent,输出结果:

Test state change.

很好,达到了我们想要的效果,而且代码量也减小了,但是真的可以做到完全的防止组件无谓的render吗?让我们来看看PureComponent的实现原理

最重要的代码在下面的文件里面,当然这个是React 16.2.0版本的引用

/node_modules/fbjs/libs/shallowEqual

大致的比较步骤是:

1.比较两个Obj对象是否完全相等用===判断

2.判断两个Obj的键数量是否一致

3.判断具体的每个值是否一致

不过你们发现没有,他只是比对了第一层次的结构,如果对于再多层级的结构的话就会有很大的问题

来让我们修改源代码再来尝试:

class A extends PureComponent {
    constructor(props){
        super(props);
    }
    static propTypes = {
        value:PropTypes.number,
        obj:PropTypes.object
    };
    static defaultProps = {
        value:0,
        obj:{}
    };
    componentDidUpdate() {
        console.log("A componentDidUpdate");
    }
    render (){
        return (
            <div />
        )
    }
}

class Test extends Component {
    constructor(props) {
        super(props);
        this.state={
            value:0,
            obj:{a:{b:123}}
        };
    }
    static propTypes = {};
    static defaultProps = {};
    componentDidMount() {
        setTimeout(()=>{
            console.log("Test state change.");
            let {obj,value} = this.state;
            //这里修改了里面a.b的值  
            obj.a.b=456;
            this.setState({
                value:value+1,
                obj:obj
            })
        },100);
    }
    render() {
        let {
            state
        } = this;
        let {
            value,
            obj
        } = state;
        return (
            <A obj={obj} />
        )
    }
}

输出结果:

Test state change.

这里不可思议吧!这也是很多人对引用类型理解理解不深入所造成的,对于引用类型来说可能出现引用变了但是值没有变,值变了但是引用没有变,当然这里就暂时不去讨论js的数据可变性问题,要不然又是一大堆,大家可自行百度这些

那么怎么样做才能真正的处理这样的问题呢?我先增加一个基类:

import React ,{Component} from 'react';
import {is} from 'immutable';
class BaseComponent extends Component {
    constructor(props, context, updater) {
        super(props, context, updater);
    }
    shouldComponentUpdate(nextProps, nextState) {
        const thisProps = this.props || {};
        const thisState = this.state || {};
        nextState = nextState || {};
        nextProps = nextProps || {};
        if (Object.keys(thisProps).length !== Object.keys(nextProps).length ||
            Object.keys(thisState).length !== Object.keys(nextState).length) {
            return true;
        }
        for (const key in nextProps) {
            if (!is(thisProps[key], nextProps[key])) {
                return true;
            }
        }
        for (const key in nextState) {
            if (!is(thisState[key], nextState[key])) {
                return true;
            }
        }
        return false;
    }
}
export default BaseComponent

大家可能看到了一个新的东西Immutable,不了解的可以自行百度或者 Immutable 常用API简介Immutable 详解

我们来改写之前的代码:

import React, {PureComponent,Component} from "react"
import PropTypes from "prop-types"
import Immutable from "immutable"
import BaseComponent from "./BaseComponent"
class A extends BaseComponent {
    constructor(props){
        super(props);
    }
    static propTypes = {
        value:PropTypes.number,
        obj:PropTypes.object
    };
    static defaultProps = {
        value:0,
        obj:{}
    };
    componentDidUpdate() {
        console.log("A componentDidUpdate");
    }
    render (){
        return (
            <div />
        )
    }
}
class Test extends Component {
    constructor(props) {
        super(props);
        this.state={
            value:0,
            obj:Immutable.fromJS({a:{b:123}})
        };
    }
    static propTypes = {};
    static defaultProps = {};
    componentDidMount() {
        setTimeout(()=>{
            console.log("Test state change.");
            let {obj,value} = this.state;
            //注意,写法不一样了
            obj = obj.setIn(["a","b"],456);
            this.setState({
                value:value+1,
                obj:obj
            })
        },100);
    }
    render() {
        let {
            state
        } = this;
        let {
            value,
            obj
        } = state;
        return (
            <A obj={obj} />
        )
    }
}

执行结果:

Test state change.
A componentDidUpdate

这样也达到了我们想要的效果

当然,还有一种比较粗暴的办法就是直接把obj换成一个新的对象也同样可以达到跟新的效果,但是可控性不大,而且操作不当的话也会导致过多的render,所以还是推荐使用immutable对结构层级比较深的props进行管理


上面的一大堆主要是讲述了对基本类型以及Object(Array 其实也是Object,这里就不单独写示例了)类型传值的优化,下面我们来讲述关于function的传值

function其实也是Object,但是纯的function比较特么,他没有键值对,无法通过上面提供的方法去比对两个function是否一致,只有通过引用去比较,所以改不改引用成为了关键

改了下代码:

import React, {PureComponent,Component} from "react"
import PropTypes from "prop-types"
import Immutable from "immutable"
import BaseComponent from "./BaseComponent"
class A extends BaseComponent {
    constructor(props){
        super(props);
    }
    static propTypes = {
        value:PropTypes.number,
        obj:PropTypes.object,
        onClick:PropTypes.func
    };
    static defaultProps = {
        value:0,
        obj:{}
    };
    componentDidUpdate() {
        console.log("A componentDidUpdate");
    }
    render (){
        let {
            onClick
        } = this.props;
        return (
            <div onClick={onClick} >
                你来点击试试!!!
            </div>
        )
    }
}
class Test extends Component {
    constructor(props) {
        super(props);
        this.state={
            value:0,
        };
    }
    static propTypes = {};
    static defaultProps = {};
    componentDidMount() {
        setTimeout(()=>{
            console.log("Test state change.");
            let {value} = this.state;
            this.setState({
                value:value+1,
            })
        },100);
    }
    onClick(){
        alert("你点击了一下!")
    }
    render() {
        let {
            state
        } = this;
        let {
            value,
            obj
        } = state;
        return (
            <A
                onClick={()=>this.onClick()}
            />
        )
    }
}

运行结果:

Test state change.
A componentDidUpdate

我们setState以后控件A也跟着更新了,而且还用了我们上面所用到的BaseComponent,难道是BaseComponent有问题?其实并不是,看Test组件里面A的onClick的赋值,这是一个匿名函数,这就意味着其实每次传入的值都是一个新的引用,必然会导致A的更新,我们这样干:

class Test extends Component {
    constructor(props) {
        super(props);
        this.state={
            value:0,
        };
    }
    static propTypes = {};
    static defaultProps = {};
    componentDidMount() {
        setTimeout(()=>{
            console.log("Test state change.");
            let {value} = this.state;
            this.setState({
                value:value+1,
            })
        },100);
    }
    onClick=()=>{
        alert("你点击了一下!")
    };
    render() {
        let {
            state
        } = this;
        let {
            value
        } = state;
        return (
            <A
                onClick={this.onClick}
            />
        )
    }
}

输出结果:

Test state change.

嗯,达到我们想要的效果了,完美!

不过我还是发现有个问题,如果我在事件或者回调中需要传值就痛苦了,所以在写每个组件的时候,如果有事件调用或者回调的话最好定义一个接收任何类型的属性,最终的代码类似下面这样

import React, {PureComponent, Component} from "react"
import PropTypes from "prop-types"
import Immutable from "immutable"
import BaseComponent from "./BaseComponent"
class A extends BaseComponent {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        value: PropTypes.number,
        obj: PropTypes.object,
        onClick: PropTypes.func,
        //增加data传值,接收任何类型的参数
        data: PropTypes.any
    };
    static defaultProps = {
        value: 0,
        obj: {},
        data: ""
    };
    componentDidUpdate() {
        console.log("A componentDidUpdate");
    }
    //这里也进行了一些修改
    onClick = () => {
        let {
            onClick,
            data
        } = this.props;
        onClick && onClick(data);
    };
    render() {
        return (
            <div onClick={this.onClick}>
                你来点击试试!!!
            </div>
        )
    }
}
class Test extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: 0,
        };
    }
    static propTypes = {};
    static defaultProps = {};
    componentDidMount() {
        setTimeout(() => {
            console.log("Test state change.");
            let {value} = this.state;
            this.setState({
                value: value + 1,
            })
        }, 100);
    }
    onClick = () => {
        alert("你点击了一下!")
    };
    render() {
        let {
            state
        } = this;
        let {
            value
        } = state;
        return (
            <A
                onClick={this.onClick}
                data={{message: "任何我想传的东西"}}
            />
        )
    }
}

总结一下:

1.编写React组件的时候使用自定义组件基类作为其他组件的继承类

2.使用Immutable管理复杂的引用类型状态

3.传入function类型的时候要传带引用的,并且注意预留data参数用于返回其他数据



作者:幺儿你去哪里呀
链接:https://www.jianshu.com/p/4dbef0d0701b
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自blog.csdn.net/sinat_17775997/article/details/82781524