簡體   English   中英

React-Native:FlatList 重新渲染每個項目

[英]React-Native: FlatList re-rendering every single item

所以我有一個 FlatList,它被提供了一個項目數組。 當我滾動到底部時,我將更多項目附加到該數組的末尾並顯示給用戶。

問題是當我們添加到我們的項目數組時,每個項目都會被渲染,有時甚至被渲染兩次。

這里簡化了代碼。 /r/reactnative 無法回答這個問題。

constructor(props) {
super(props);
this.state = {itemsTest: ['A', 'A', 'A', 'A']}
}

render() {


// Key is fine, since none of my items are changing indexes. I am just adding new items.
return (

<FlatList

keyExtractor={(item,index) => index}

scroll

data={this.state.itemsTest}

renderItem={({item, index}) => <View style={{width: windowWidth}}><Text>{item}</Text></View>

onEndReached={() => this.nextItemsTest()}

onEndReachedThreshold={0.2}

</FlatList>
)
}







nextItemsTest() {

// From suggestions below, just add an element to this array.

console.log('nextItemsTest');

const x = ['A'];

// Have worked with many variations of setting state here. I don't think this is the issue.
this.setState((prevState) => ({itemsTest: [...prevState.itemsTest, ...x],}));}

這是輸出。 每次設置我的狀態時,每個項目都會重新渲染(甚至兩次)。

我只想重新渲染沒有改變的項目。 謝謝你。

在此處輸入圖片說明

您可以創建另一個組件,它是一個純組件,而不是直接在您的平面列表渲染中使用視圖。 所以它只會在數據改變時重新渲染。 例如,對於您的情況,它只重新渲染每個項目一次。

這是解決方案

1st 創建一個像這樣的純組件

 class SmartView extends PureComponent { render() { const {item, index} = this.props; return ( <View style={{height: 300}}> {console.log('rendering', index)} <Text>{item}</Text> </View> ); } }

然后像這樣在你的平面列表中用SmartView替換View

 <FlatList keyExtractor={(item, index) => index.toString()} data={this.state.itemsTest} renderItem={({item, index}) => <SmartView item= {item} index={index} />} onEndReached={() => this.nextItemsTest()} onEndReachedThreshold={0.2} />

暫無
暫無

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

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