Ask*_*_29 1 javascript reactjs
我正在尝试减少子组件中不必要的渲染。当子组件触发状态修改时,所有其他不受影响的组件都会重新渲染(当然是在虚拟 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>
)
}
Run Code Online (Sandbox Code Playgroud)
我开始在 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 };
Run Code Online (Sandbox Code Playgroud)
有了这个,我得到了与没有使用 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
Run Code Online (Sandbox Code Playgroud)
handleClick 来自钩子,我使用 useCallback 来获取始终相同的引用,我没有其他道具,所以我不知道为什么
prevProps === nextProps
Run Code Online (Sandbox Code Playgroud)
仍然是假的。这种情况发生在其他子组件中,所以我不想在每个子组件中添加自定义函数,接下来我应该检查什么以确保 prevProps === nextProps 为 true?
小智 5
如果你用===JS就会做一个参考比较,你需要的是深度比较。为此,您可以使用类似的内容 => /sf/answers/2689152581/
或者使用 lodash [ https://lodash.com/docs/]使其更容易;
使用 lodash 将会是这样的:
const _ = require("lodash");
_.isEqual(prevProps, nextProps);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6843 次 |
| 最近记录: |