【发布时间】:2019-10-27 04:23:07
【问题描述】:
我正在尝试减少子组件中不必要的渲染。当子组件触发状态修改时,所有其他未受影响的组件都会重新渲染(当然是在虚拟 DOM 中)。 我正在使用 React.memo,但如果我让与 React.memo 进行比较,则渲染结果与我没有使用它时相同。
为了调查问题,我尝试控制台记录道具。
第一个组件根据 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 每个道具。
prevProps === nextProps //false
prevProps.itemType === nextProps.itemType //true
prevProps.text === nextProps.text //true
prevProps.handleClick === nextProps.handleClick //true
prevProps.activeClass === nextProps.activeClass //true
handleClick 来自一个钩子,我使用 useCallback 来获得始终相同的引用,我没有其他道具所以我不知道为什么
prevProps === nextProps
仍然是错误的。这发生在其他子组件中,所以我不想在每个子组件中添加自定义函数, 接下来我应该检查什么以确保 prevProps === nextProps 为真?
【问题讨论】:
标签: javascript reactjs