相关疑难解决方法(0)

函数组件中的shouldComponentUpdate

我有一个关于React的问题shouldComponentUpdate(当没有被覆盖时).我更喜欢纯粹的功能组件,但我担心它每次都会更新,即使道具/状态没有改变.所以我正在考虑使用PureComponent类.

我的问题是:功能组件shouldComponentUpdate是否与PureComponents 具有相同的检查?或者它每次更新?

reactjs

24
推荐指数
4
解决办法
9956
查看次数

如何在React Hooks中使用shouldComponentUpdate?

我一直在阅读以下链接:
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;
}
Run Code Online (Sandbox Code Playgroud)

我该如何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> …
Run Code Online (Sandbox Code Playgroud)

javascript functional-programming reactjs react-hooks

4
推荐指数
2
解决办法
3612
查看次数