如何防止我的功能组件使用React备忘录或React钩子重新渲染? [英] How can I prevent my functional component from re-rendering with React memo or React hooks?

查看:144
本文介绍了如何防止我的功能组件使用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);

这篇关于如何防止我的功能组件使用React备忘录或React钩子重新渲染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆