Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

javascript - How to use shouldComponentUpdate with React Hooks?

I've been reading these links:
https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-shouldcomponentupdate
https://reactjs.org/blog/2018/10/23/react-v-16-6.html

In the first link it says (https://reactjs.org/docs/hooks-faq.html#from-classes-to-hooks):

shouldComponentUpdate: See React.memo

The second link also states that:

Class components can bail out from rendering when their input props are the same using PureComponent or shouldComponentUpdate. Now you can do the same with function components by wrapping them in React.memo.


What is desired:

I want Modal to render only when the Modal is visible (managed by this.props.show)

For class component:

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

How can I use memo instead in a functional component - here, in Modal.jsx?


The related code:

Functional component Modal.jsx (I don't know how to check for 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;

The part of class component PizzaMaker jsx that renders Modal:



 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>
    );

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the documentation for React.memo

You can pass a function to control the comparison :

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

when the function returns true, the component will not be re-rendered


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...