我知道您可以通过将数组作为可选的第二个参数传递来告诉React跳过效果。
例如:
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
Run Code Online (Sandbox Code Playgroud)
但是,如果我想控制比较怎么办?添加我自己的比较逻辑。
我希望React.memo可以将一个函数作为第二个参数传递给您。
虽然很明显为什么React默认情况下不对它的所有功能组件执行 React.memo,但我们应该在需要时自己包装我们的功能组件。
就我而言,我有一个大型 React 项目,其结构如下:
const MyBigApp = () => {
const shouldShowX = useSelector(getShouldShowX);
const shouldShowY = useSelector(getShouldShowY);
// Many more selectors
return (
<>
{shouldShowX && <ComplexComponentX />}
{shouldShowY && <ComplexComponentY />}
{/* many more components based on different selectors like above */}
</>
);
};
Run Code Online (Sandbox Code Playgroud)
我所有的业务逻辑都在 redux 中,组件在useSelector内部使用以从存储中获取数据。
用 包装我的所有子组件是否有意义React.memo,因为根级别的任何选择器的更改都会导致我的整个应用程序重新渲染?
早些时候,connect我们自动获得了一个记忆化组件,它比较了自定义道具和作为道具传递给组件的存储值,那么我们现在是否应该在未接收任何道具的组件中使用时始终手动执行?React.memouseSelector
我一直在阅读以下链接:
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)