如何在React Hooks中使用shouldComponentUpdate?

时间:2019-05-24 17:44:19

标签: javascript reactjs functional-programming 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

第二个链接还指出:

如果使用PureComponent或shouldComponentUpdate输入的道具相同,则类组件可以免于渲染。现在,您可以通过将功能组件包装在React.memo中来对它们进行相同的操作。


需要什么:

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

对于类组件:

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

如何在功能组件中(此处为Modal.jsx)使用memo


相关代码:

功能组件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;

类组件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>
    );

3 个答案:

答案 0 :(得分:5)

您还可以在以下导出语句中使用

export default memo(Modal, (prevState, nextState) => prevState.show === nextState.show) ;

答案 1 :(得分:2)

这是documentation for React.memo

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

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

当函数返回true时,组件将不会重新呈现

答案 2 :(得分:0)

让我们假设您有一个名为CountDown的功能性有状态组件,它会收到一个名为prop的{​​{1}}并递减该值直至其达到0。在React的反应系统中,您应该将此道具以value的状态进行序列化,并将其更改为达到0。让我们编写这样的组件:

CountDown

注意到问题了吗?通过将您的const CountDown = ({value}) =>{ const [current, setter] = useState(value) if(current > 0) setter(current-1) return( <div>{current}</div> ) } 序列化为value的状态,我们只是失去了只要此prop发生更改就可以重新渲染的功能。如果CountDown从未更改,那么就没有问题,但是如果这样做,则需要确保value组件也重新呈现。我们可以使用CountDown钩子来做到这一点。

useEffect

通过将依赖项数组作为第二个参数传递,我们告诉React仅当作为依赖项传递的值之一发生更改时,才对该给定组件执行更新。