【发布时间】:2021-12-23 22:23:22
【问题描述】:
有一个组件接收道具。
props 有一个数组的形状,对于这个数组的每个元素,一个函数将返回一个不同的组件来渲染。
function MainComponent ({ data }) => { // data is props, an array
const specialFunction = (index) => {
switch (index) {
case 0:
return <Component0 />;
case 1:
return <Component1 />;
case 2:
return <Component2 />;
default:
return null;
}
};
...
return (
...
data.map((item, index) => {
... // do other stuff with item
<div>{specialFunction(index)}</div> // the function that we talk about
...
);
如果道具不会改变,有没有办法记住这个结果?或者有什么更好的写法?
【问题讨论】:
-
你有没有尝试明显的 -
useMemo(specialFunction, [index])? -
你可以试试
useMemo或memo。 -
对于函数,也可以使用useCallback。
-
在您的示例中,该函数可能位于
MainComponent之外。
标签: javascript reactjs typescript react-hooks react-usememo