簡體   English   中英

在 React 組件渲染中初始化一個數組(在性能方面)

[英]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.ComponentReact.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM