Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How can I prevent my functional component from re-rendering with React memo or React hooks?

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

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

Here's what my component looks like:

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;
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...