如何将React.memo应用于数组中的所有组件



是否可以将React.memo应用于带有for循环的组件数组
假设我有以下三个组件:

const Item1 = (props) => {
const { index } = props;
return (
<div>{index}</div>
);      
}
const Item2 = (props) => {
const { index } = props;
return (
<div>{index}</div>
);      
}
const Item3 = (props) => {
const { index } = props;
return (
<div>{index}</div>
);      
}

我可以在我的应用程序组件中执行此操作吗?

const App = (props) => {
const items = [Item1, Item2, Item3];
let itemarray = [];
let index = 0;
for (const item of items) {
const MemoizedItem = React.memo(item);
itemarray.push(<MemoizedItem key={index} index={index} />);
index++;
}
return (
<div>
{itemarray}
</div>
);
}

我知道我可以为这三个项目中的每一个硬编码React.memo(见下文(,但我希望能够迭代。

const Item1 = React.memo((props) => {
const { index } = props;
return (
<div>{index}</div>
);      
});
//...same for Item2 and Item3

在渲染过程中调用React.memo不是一个好主意。它将产生与预期目标完全相反的效果。您将强制它执行额外的渲染,而不是跳过渲染。

当您调用React.memo并传入一个组件时,返回的是一种新类型的组件。不是新实例,而是新类型。react告诉从一个渲染到下一个渲染发生了什么变化的主要方式是比较组件上的类型。如果类型发生了更改,则会认为它是不同的,因此旧组件将被卸载,新组件将被重新安装。每次App渲染时,它都会创建全新类型的组件,这意味着从一个渲染到下一个渲染都无法保存任何内容。

我建议您只使用React.Memo来实现Item1、Item2和Item3。例如:

const Item1 = React.memo((props) => {
const { index } = props;
return (
<div>{index}</div>
);      
})

但是,如果你绝对需要动态地进行,那么你需要确保只进行一次,这基本上意味着你需要对记忆进行记忆:

const App = (props) => {
const items = [Item1, Item2, Item3];
const memoizedItems = useMemo(() => {
return items.map(item => React.Memo(item));
}, [])
let itemarray = [];
let index = 0;
for (const MemoizedItem of memoizedItems) {
itemarray.push(<MemoizedItem key={index} index={index} />);
index++;
}
return (
<div>
{itemarray}
</div>
);
}

编辑:不建议使用此答案。它完全破坏了React Memo的要点。检查已接受的答案,因为它解释了正确的方法。

我认为这会奏效。我更愿意使用数组的map方法来做这件事

const App = (props) => {
const items = [Item1, Item2, Item3];
return (
<div>
{items.map((item, index) => {
const MemoizedItem = React.memo(item);
return <MemoizedItem key={index} index={index} />
}}
</div>
);
}

最新更新