如何防止我的功能组件使用 React 备忘录或 React 钩子重新渲染? [英] How can I prevent my functional component from re-rendering with React memo or React hooks?
问题描述
当 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 hooks/React memo?
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屋!