前端开发那些事儿

React.Component,React.PureCompon

2021-03-15  本文已影响0人  弱冠而不立

React.Component,React.PureComponent的区别

React.PureComponentReact.Component 很相似。两者的区别在于 React.Component并未实现 shouldComponentUpdate(),而 React.PureComponent 中以浅层对比 prop 和 state 的方式来实现了该函数。

这句话的意思并不是,React.Component 里没有这个 shouldComponentUpdate() 生命周期钩子.,而是想表达,Component 有这个 shouldComponentUpdate() 但是需要你去根据你的组件逻辑,自己去返回 true 或 false 来控制是否更新;而 PureComponent 已经帮你在这个方法里实现了浅比较props和state来自动判断需不需要更新。

但需要注意的是:React.PureComponent 中的 shouldComponentUpdate() 仅作对象的浅层比较。如果对象中包含复杂的数据结构,则有可能因为无法检查深层的差别,产生错误的比对结果。仅在你的 props 和 state 较为简单时,才使用 React.PureComponent

这个例子可以看到 PureComponet 和 Compnent 传入相同数据的区别

React.memo

React.memo 为高阶组件,它可以传入一个 React 组件作为参数。
如果你的组件在相同 props 的情况下渲染相同的结果,那么你可以通过将其包装在 React.memo 中调用,以此通过记忆组件渲染结果的方式来提高组件的性能表现。这意味着在这种情况下,React 将跳过渲染组件的操作并直接复用最近一次渲染的结果。

简单来说就是,被包裹的组件如果两次更新传入的 props 都相同,则直接复用上一次的更新。

这个例子可以看到三者传入相同数据的区别

代码示例

import ReactDOM from "react-dom";

import React, { useEffect } from "react";

class PureCp extends React.PureComponent {
  componentDidUpdate() {
    console.log("PureCp---componentDidUpdate");
  }

  render() {
    return <h3>PureCp: {this.props.msg}</h3>;
  }
}

class Cp extends React.Component {
  componentDidUpdate() {
    console.log("Cp---componentDidUpdate");
  }

  render() {
    return <h3>Cp: {this.props.msg}</h3>;
  }
}

const MemoCp = React.memo(function Foo(props) {
  useEffect(() => {
    console.log("MemoCp---useEffect");
  }, [props]);
  return <h3>MemoCp: {props.msg}</h3>;
});

class Fa extends React.Component {
  constructor() {
    super();
    this.state = {
      msg: ""
    };
    this.iptRef = React.createRef();
    this.handleBtnClick = () => {
      this.setState({
        msg: this.iptRef.current.value
      });
    };
  }

  render() {
    return (
      <div>
        <input ref={this.iptRef} />
        <button onClick={this.handleBtnClick}>Emit</button>
        <PureCp msg={this.state.msg} />
        <Cp msg={this.state.msg}></Cp>
        <MemoCp msg={this.state.msg} />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.unstable_createRoot(rootElement).render(<Fa />);
上一篇 下一篇

猜你喜欢

热点阅读