小编典典

如何在React Hooks中使用shouldComponentUpdate?

reactjs

我一直在阅读以下链接:
https : //reactjs.org/docs/hooks-faq.html#how-do-i-
implement-shouldcomponentupdate
https://reactjs.org/blog/2018/10/23/react
-v-16-6.html

在第一个链接中显示为(https://reactjs.org/docs/hooks-faq.html#from-classes-to-
hooks):

shouldComponentUpdate:请参见React.memo

第二个链接还指出:

当使用PureComponent或shouldComponentUpdate输入类相同时,类组件可以从渲染中解脱出来。现在,您可以通过将功能组件包装在React.memo中来对它们进行相同的操作。


需要什么:

我希望Modal仅在可见Modal时呈现(由this.props.show管理)

对于类组件:

shouldComponentUpdate(nextProps, nextState) {
    return nextProps.show !== this.props.show;
}

我该如何memo在功能组件中使用-在这里,在Modal.jsx中?


相关代码:

功能组件Modal.jsx(我不知道如何检查props.show)

import React, { useEffect } from 'react';
import styles from './Modal.module.css';
import BackDrop from '../BackDrop/BackDrop';

const Modal = React.memo(props => {
  useEffect(() => console.log('it did update'));

  return (
    <React.Fragment>
      <BackDrop show={props.show} clicked={props.modalClosed} />
      <div
        className={styles.Modal}
        style={{
          transform: props.show ? 'translateY(0)' : 'translateY(-100vh)',
          opacity: props.show ? '1' : '0'
        }}>
        {props.children}
      </div>
    </React.Fragment>
  );
});

export default Modal;

呈现Modal的类组件PizzaMaker jsx的一部分:

 return (
      <React.Fragment>
        <Modal show={this.state.purchasing} modalClosed={this.purchaseCancel}>
          <OrderSummary
            ingredients={this.state.ingredients}
            purchaseCancelled={this.purchaseCancel}
            purchaseContinued={this.purchaseContinue}
            price={this.state.totalPrice}
          />
        </Modal>
        ...
      </React.Fragment>
    );

阅读 3945

收藏
2020-07-22

共1个答案

小编典典

这是React.memo文档

您可以通过一个函数来控制比较:

const Modal = React.memo(
  props => {...},
  (prevProps, nextProps) => prevProps.show === nextProps.show
);

当函数返回时true,将不会重新渲染组件

2020-07-22