繁体   English   中英

如何在 React Hooks 中使用 shouldComponentUpdate?

[英]How to use shouldComponentUpdate with React Hooks?

我一直在阅读这些链接:
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

第二个链接还指出:

当类组件的输入 props 相同时,可以使用 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>
    );

这是React.memo文档

您可以传递一个函数来控制比较:

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

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

您也可以在导出语句中使用,例如:

export default memo(Modal, (prevProps, nextProps) => prevProps.show === nextProps.show) ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM