在 React 组件渲染中初始化数组(就性能而言)



众所周知,我们不应该在渲染中使用匿名函数,因为它们将在每次渲染时重新创建。但是像这样的对象数组呢:

// 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} />;
}

我想数组(和里面的对象(是通过引用存储的,所以当组件被重新渲染时,解释器会看到这是相同的引用,并且不会重新创建数组。我的假设正确吗?

不,这不是同一个引用。您正在创建新数组,每个渲染中都有新对象。如果它是完全静态的,你可以从函数中提取它以保持相同的 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} />;
);

不幸的是,当使用React.ComponentReact.FunctionnalComponent时,似乎每一个更改都会重新渲染整个数组。

我们可以考虑使用React.PureComponent作为此问题的解决方法,更多信息在这里:https://codeburst.io/react-array-re-render-performance-ee23f34c5d66

最好将 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} />;
}

最新更新