如何使用React.memo()

2026-05-02 12:25:25 210
分类:react

转载自:https://www.jianshu.com/p/b3d07860b778

包装函数

React v16.6.0出了一些新的包装函数(wrapped functions),一种用于函数组件PureComponent / shouldComponentUpdate形式的React.memo()

本篇将介绍React.memo()的使用场景

React.memo()是一个高阶函数,它与 React.PureComponent类似,但是一个函数组件而非一个类。

import React from 'react';

export default class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            date: new Date()
        }
    }

    componentDidMount() {
        setInterval(() => {
            this.setState({
                date: new Date()
            })
        }, 1000)
    }

    render() {
        return (
            <div>
                <Child seconds={1}/>
                <div>{this.state.date.toString()}</div>
            </div>
        )
    }
}

现在有一个显示时间的组件,每一秒都会重新渲染一次,对于Child组件我们肯定不希望也跟着渲染,所有需要用到PureComponent

PureComponent

class Child extends React.PureComponent {
    render() {
        console.log('I am rendering');
        return (
            <div>I am update every {this.props.seconds} seconds</div>
        )
    }
}

现在新出了一个React.memo()可以满足创建纯函数而不是一个的需求

React.memo()

function Child({seconds}) {
    console.log('I am rendering');
    return (
        <div>I am update every {seconds} seconds</div>
    )
};
export default React.memo(Child)

React.memo()可接受2个参数,第一个参数为纯函数的组件,第二个参数用于对比props控制是否刷新,与shouldComponentUpdate()功能类似。