簡體   English   中英

由於多種樣式,React組件重新渲染

[英]React component re-renders due to multiple styles

當我傳遞多種樣式時,我面臨渲染問題:

<StyledComponent style={[styles.styleOne, styles.styleTwo]} />

如果重新渲染中包含組件StyledComponent,則即使道具沒有更改,StyledComponent也將重新渲染。

我知道,如果父組件調用setState,則無論孩子自己的道具實際發生變化,它的孩子都會重新渲染。 我試圖利用PureComponent和React.memo。 但是,我的子組件仍在重新渲染。 看來問題在於我發送樣式的方式。 如果我這樣傳遞一種樣式:

<StyledComponent style={styles.styleOne} />

PureComponent / React.memo有效。 但是,如果我的組件的樣式是這樣的:

<StyledComponent style={[styles.styleOne, styles.styleTwo]} />

然后每次都會重新渲染。

這是因為我在父組件的每個渲染實例化了一個新數組 ,而PureComponent / React.memo無法拾取那些相同的樣式。

所以我的問題是,如何在一個組件上使用多種樣式而不必在每個子組件上編寫自定義的shouldComponentUpdate? 由於我正在使用較舊的Android設備,因此渲染明顯降低了我的應用程序的性能,因此,我想盡量減少所需的渲染。

這是演示此情況的小吃: https : //snack.expo.io/@tnortman/styles-r-stupid

如果您不想實現自定義的shouldComponentUpdate,則需要確保該數組通過===檢查。 取決於更改方式或更改方式,有兩種可能性。 如果它永遠不會改變,那就是最簡單的方法:只需一次創建數組,然后對其進行引用。 例如:

const styles = StyleSheet.Create({
  styleOne: {
    backgroundColor: 'red',
  },
  styleTwo: {
    padding: 40,
  },
});

// Note that this line is not in render
const combined = [styles.styleOne, styles.styleTwo];

// ...

// in render:

<StyledPureComponent style={combined} />

如果有可能改變它,那么您需要添加一些代碼來管理它。 最有可能的是,我將創建一個生成數組的記憶函數,並且僅在相關內容發生更改時才重新計算。 例如,這是一個基於prop的示例,該示例有時包括style2,有時不包括:

// Just an example; you could use a different library or implement it yourself
import memoize from "memoize-one";

const combineStyles = memoize((shouldIncludeStyleTwo) => {
  const styles = [styles.styleOne];
  if (shouldIncludeStyleTwo) {
     styles.push(styles.styleTwo);
  }
  return styles;
});

// ...

<StyledPureComponent style={combineStyles(this.props.something)} />

將styles數組移出該類的實例變量,然后通過props傳遞引用。 這樣,它就不是每個渲染的新數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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