我正在重构我们的一些组件,因此我正在尝试合并 memoization,因为某些组件可能会使用相同的值重新呈现(例如,除非它们相同,否则热链接的图像 URL)。
我有一个简单的组件:
const CardHeader = props => {
// img is a stringand showAvatar is a boolean but it's always true
const { ..., showAvatar, img } = props;
return (
<CardHeader>
<ListItem>
// AvatarImage shouldn't re-render if img is the same as previous
{showAvatar && <AvatarImage img={img} />
</ListItem>
</CardHeader>
);
}
然后是AvatarImage:
const AvatarImage = React.memo(props => {
console.log("why is this still re-rendering when the img value hasn't changed?");
const { img } = props;
return (
<ListItemAvatar>
{img ?
<Avatar src={img} />
:
<Avatar>
Some initials
</Avatar>
}
</ListItemAvatar>
);
});
我也试过传入备忘录的第二个参数:
(prevProps, nextProps) => {
return true; // Don't re-render!
}
但是 console.log 仍然每次都显示。我显然在这里遗漏了一些东西,或者不太明白这是如何工作的。这个组件低了几个级别,但是如果它每次都可用,它就会传入 img,所以我希望它知道 img 是否在上一次渲染中被传递,并且它知道不再重新渲染它是相同的但出于某种原因,它会吗?
谢谢大家。非常感谢。