如何防止我的功能组件使用React备忘录或React钩子重新渲染?

如何防止我的功能组件使用React备忘录或React钩子重新渲染?

问题描述:

hiddenLogo更改值时,将重新渲染组件.我希望此组件从不重新渲染,即使其道具发生了变化.使用类组件,我可以这样实现sCU:

When hiddenLogo changes value, the component is re-rendered. I want this component to never re-render, even if its props change. With a class component I could do this by implementing sCU like so:

shouldComponentUpdate() {
  return false;
}

但是有没有办法处理React挂钩/React备忘录?

But is there a way to do with with React hooks/React memo?

这是我的组件的样子:

import React, { useEffect } from 'react';
import PropTypes from 'prop-types';

import ConnectedSpringLogo from '../../containers/ConnectedSpringLogo';

import { Wrapper, InnerWrapper } from './styles';
import TitleBar from '../../components/TitleBar';

const propTypes = {
  showLogo: PropTypes.func.isRequired,
  hideLogo: PropTypes.func.isRequired,
  hiddenLogo: PropTypes.bool.isRequired
};

const Splash = ({ showLogo, hideLogo, hiddenLogo }) => {
  useEffect(() => {
    if (hiddenLogo) {
      console.log('Logo has been hidden');
    }
    else {
      showLogo();

      setTimeout(() => {
        hideLogo();
      }, 5000);
    }
  }, [hiddenLogo]);

  return (
    <Wrapper>
      <TitleBar />
      <InnerWrapper>
        <ConnectedSpringLogo size="100" />
      </InnerWrapper>
    </Wrapper>
  );
};

Splash.propTypes = propTypes;

export default Splash;

正如G.aziz所说,React.Memo的功能类似于纯组件.但是,您还可以通过向其传递一个定义为相等的函数来调整其行为.基本上,此函数为shouldComponentUpdate,不同之处在于,如果希望它渲染,则返回true.

As G.aziz said, React.Memo functions similarly to pure component. However, you can also adjust its behavior by passing it a function which defines what counts as equal. Basically, this function is shouldComponentUpdate, except you return true if you want it to not render.

const areEqual = (prevProps, nextProps) => true;

const MyComponent = React.memo(props => {
  return /*whatever jsx you like */
}, areEqual);