[英]React.memo prevProps always different from nextProps even if props never changes
I'm trying to reduce unnecessary rendering in child components. 我试图减少子组件中不必要的渲染。 When a child component trigger a state modification all others unaffected components get re-rendered (in virtual DOM of course).
当子组件触发状态修改时,所有其他不受影响的组件将重新呈现(当然是在虚拟DOM中)。 I'm using React.memo but if I let the comparison to React.memo the renders are the same as if I wasn't using it.
我正在使用React.memo,但是如果让我与React.memo进行比较,则呈现效果与未使用它时相同。
To investigate the problem I tried to console.log the props. 为了调查问题,我尝试用console.log道具。
The first component render a list of components based on props and on a template from another file. 第一个组件基于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>
)
}
I'm starting using memo in the ListItem component 我开始在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 };
Whit this I get the same renders as if I wasn't using React.memo, so I console.log every single props. 我得到的渲染效果就像我没有使用React.memo一样,因此我会console.log每个道具。
prevProps === nextProps //false
prevProps.itemType === nextProps.itemType //true
prevProps.text === nextProps.text //true
prevProps.handleClick === nextProps.handleClick //true
prevProps.activeClass === nextProps.activeClass //true
handleClick is from an hook and I used useCallback to get always the same reference, I don't have other props so I don't know why handleClick来自一个钩子,我使用useCallback来获得始终相同的引用,我没有其他道具,所以我不知道为什么
prevProps === nextProps
is still false. 仍然是错误的。 This happens in others child components, so I don't want to add a custom function in every one of them, what should I check next to ensure that prevProps === nextProps is true?
这在其他子组件中也会发生,所以我不想在每个子组件中添加自定义函数,接下来我应该检查什么以确保prevProps === nextProps为真?
If you use ===
JS will make a reference comparison and what you need is a deep comparison. 如果使用
===
JS将进行参考比较,而您需要的是深度比较。 For do this you could use something like this => https://stackoverflow.com/a/38416465/8548193 为此,您可以使用类似== https://stackoverflow.com/a/38416465/8548193的方法
or use lodash [ https://lodash.com/docs/] to make it more easier; 或使用lodash [ https://lodash.com/docs/]使其更容易;
with lodash it will be something like this: 使用lodash会是这样的:
const _ = require("lodash");
_.isEqual(prevProps, nextProps);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.