我正在尝试减少子组件中不必要的渲染。当子组件触发状态修改时,所有其他不受影响的组件都会重新渲染(当然是在虚拟 DOM 中)。 我正在使用 React.memo,但如果我与 React.memo 进行比较,渲染效果与我没有使用它时相同。
为了调查这个问题,我尝试 console.log 属性。
第一个组件根据 props 和另一个文件中的模板渲染组件列表。
const List = props => {
return (
<div id="List">
{template[props.status].map(
el =>
<ListItem
activeClass={props.active === el.type ? 'active' : ''}
handleClick={props.handleClick}
key={el.type}
itemType={el.type}
text={el.text} />
) }
</div>
)
}
我开始在 ListItem 组件中使用备忘录
const ListItem = React.memo( props => {
return (
<button
className={props.activeClass}
onClick={props.handleClick}
title={props.itemType}
value={props.itemType} >
{props.text}
</button>
)
}, (prevProps, nextProps) => {
prevProps === nextProps };
这样我得到的渲染效果就好像我没有使用 React.memo 一样,所以我 console.log 每一个 props。
prevProps === nextProps //false
prevProps.itemType === nextProps.itemType //true
prevProps.text === nextProps.text //true
prevProps.handleClick === nextProps.handleClick //true
prevProps.activeClass === nextProps.activeClass //true
handleClick 来自一个钩子(Hook),我使用 useCallback 来获取始终相同的引用,我没有其他 Prop ,所以我不知道为什么
prevProps === nextProps
仍然是错误的。这种情况发生在其他子组件中,所以我不想在每个子组件中添加自定义函数, 接下来我应该检查什么以确保 prevProps === nextProps 为 true?
最佳答案
如果你使用===
JS会做一个引用比较,你需要的是深度比较。为此,您可以使用类似的内容 => https://stackoverflow.com/a/38416465/8548193
或使用lodash [https://lodash.com/docs/]让事情变得更容易;
使用 lodash 会是这样的:
const _ = require("lodash");
_.isEqual(prevProps, nextProps);
关于javascript - React.memo prevProps 总是与 nextProps 不同,即使 props 永远不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56565839/