简体   繁体   English

在 React 组件渲染中初始化一个数组(在性能方面)

[英]Initialize an array in React component render (in terms of performance)

It is known that we should not use anonymous functions in render because they will be re-create on each render.众所周知,我们不应该在渲染中使用匿名函数,因为它们会在每次渲染时重新创建。 But what about an array of objects like this:但是像这样的对象数组呢:

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

I suppose that arrays (and objects inside) are stored by reference so when the component is re-rendered, the interpreter sees that this is the same reference and won't re-create the array.我想 arrays (和里面的对象)是通过引用存储的,所以当重新渲染组件时,解释器会看到这是同一个引用并且不会重新创建数组。 Is my assumption correct?我的假设正确吗?

No, it's not the same reference.不,这不是同一个参考。 You're creating new array with new objects inside on each render.您正在创建新数组,其中包含每个渲染中的新对象。 If it's completely static, you can extract it from your function to keep the same ref:如果它完全是 static,您可以从 function 中提取它以保持相同的参考:

const name = 'some-name';
const bigArray = [{id: 1, name}, {id: 2, name}];

const Component = () => (
   <AnotherComponent data={bigArray} />;
);

But in your case this array generated from prop.但在你的情况下,这个数组是从 prop 生成的。 You can use useMemo() hook to optimize it:你可以使用useMemo()钩子来优化它:

const Component = ({ name }) => (
  const bigArray = useMemo(
    () => [{id: 1, name}, {id: 2, name}],
    [ name ]
  );

   <AnotherComponent data={bigArray} />;
);

Unfortunately when using a React.Component or React.FunctionnalComponent it seems that every single change will re-render the complete array.不幸的是,当使用React.ComponentReact.FunctionnalComponent时,似乎每一次更改都会重新渲染完整的数组。

We can consider using a React.PureComponent as a workaround of this issue, more infos here: https://codeburst.io/react-array-re-render-performance-ee23f34c5d66我们可以考虑使用React.PureComponent作为解决此问题的方法,更多信息在这里: https://codeburst.io/react-array-re-render-performance-ee23f34c5d66

It is better if you move bigArray then (considering it does not change) to a more global state.如果您将 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM