[英]Initialize an array in React component render (in terms of performance)
众所周知,我们不应该在渲染中使用匿名函数,因为它们会在每次渲染时重新创建。 但是像这样的对象数组呢:
// name props is passed in so it seems like there is a point in initializing the array inside the component
const Component = ({ name }) => {
// let's imagine there is a lot of large objects
const bigArray = [{id: 1, name}, {id: 2, name}];
return <AnotherComponent data={bigArray} />;
}
我想 arrays (和里面的对象)是通过引用存储的,所以当重新渲染组件时,解释器会看到这是同一个引用并且不会重新创建数组。 我的假设正确吗?
不,这不是同一个参考。 您正在创建新数组,其中包含每个渲染中的新对象。 如果它完全是 static,您可以从 function 中提取它以保持相同的参考:
const name = 'some-name';
const bigArray = [{id: 1, name}, {id: 2, name}];
const Component = () => (
<AnotherComponent data={bigArray} />;
);
但在你的情况下,这个数组是从 prop 生成的。 你可以使用useMemo()
钩子来优化它:
const Component = ({ name }) => (
const bigArray = useMemo(
() => [{id: 1, name}, {id: 2, name}],
[ name ]
);
<AnotherComponent data={bigArray} />;
);
不幸的是,当使用React.Component
或React.FunctionnalComponent
时,似乎每一次更改都会重新渲染完整的数组。
我们可以考虑使用React.PureComponent
作为解决此问题的方法,更多信息在这里: https://codeburst.io/react-array-re-render-performance-ee23f34c5d66
如果您将 bigArray 然后(考虑到它不会改变)移动到更全局的 state 会更好。
// let's imagine there is a lot of large objects
const bigArray = [{id: 1, name}, {id: 2, name}];
// name props is passed in so it seems like there is a point in initializing the array inside the component
const Component = ({ name }) => {
return <AnotherComponent data={bigArray} />;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.