众所周知,我们不应该在渲染中使用匿名函数,因为它们将在每次渲染时重新创建。但是像这样的对象数组呢:
// 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} />;
}
我假设数组(和里面的对象)是通过引用来存储的,所以当组件被重新呈现时,解释器会看到这是相同的引用,因此不会重新创建数组。我的假设正确吗?
发布于 2019-10-10 12:46:19
不,这不是同一个引用。在每次渲染时,您都会在内部创建包含新对象的新数组。如果它是完全静态的,你可以将它从你的函数中提取出来以保持相同的ref:
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} />;
);
发布于 2019-10-10 12:51:31
不幸的是,在使用React.Component
或React.FunctionnalComponent
时,似乎每一次更改都会重新呈现整个数组。
我们可以考虑使用React.PureComponent
作为解决此问题的方法,有关详细信息,请单击此处:https://codeburst.io/react-array-re-render-performance-ee23f34c5d66
发布于 2019-10-10 12:44:52
如果您将bigArray然后(考虑到它不会改变)移动到一个更全局的状态,这会更好。
// 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} />;
}
https://stackoverflow.com/questions/58323150
复制