簡體   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