# 一. 定义

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

# 二. 参数

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

# 三. 例子

# 1.例子 1

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>
    );
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  • 现在有一个显示时间的组件,每一秒都会重新渲染一次,对于 Child 组件我们肯定不希望也跟着渲染,所有需要用到PureComponent
class Child extends React.PureComponent {
  render() {
    console.log("I am rendering");
    return <div>I am update every {this.props.seconds} seconds</div>;
  }
}
1
2
3
4
5
6
  • 现在新出了一个 React.memo()可以满足创建纯函数而不是一个类的需求
function Child({ seconds }) {
  console.log("I am rendering");
  return <div>I am update every {seconds} seconds</div>;
}
export default React.memo(Child);
1
2
3
4
5

# 2.例子 2

// 第二个参数的使用
import React from "react";

function Child({ seconds }) {
  console.log("I am rendering");
  return <div>I am update every {seconds} seconds</div>;
}

function areEqual(prevProps, nextProps) {
  if (prevProps.seconds === nextProps.seconds) {
    return true;
  } else {
    return false;
  }
}
export default React.memo(Child, areEqual);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 参考

[1] https://www.jianshu.com/p/b3d07860b778