2017-09-12 26 views
0

以下是組件代碼,每隔20張卡就會獲取一個項目並注入一個廣告,它使用分頁和卡片在用戶到達底部時添加到現有數據清單:React Native FlatList,在使用開關渲染組件時嘮叨住鑰匙

// every 20 cards, inject an advertisment 
var modulusCount = 0; 
if ((this.state.labels.length - modCount) % 20 === 0) { 
        this.state.labels.push({type: 'ad'}); 
        modulusCount++; 
       } 

_renderItem = ({item}) => { 
    switch (item.type) { 
     case 'label': 
      return <Card key={item._id} style={styles.card}> 
       <CardTitle title={item.description}/> 
       <TouchableOpacity style={styles.image} onPress={() => this._showImage(item.imagepath, item.upvotes, item._id)} activeOpacity={0.7}> 
        <CardImage seperator={false} id={item._id} inColumn={false} source={{uri: item.imagepath}}/> 
       </TouchableOpacity> 
      </Card>; 
     case 'ad': 
      return (this.state.fbad && this.state.ads ? 
       <View key={item._id}> 
        <Card style={styles.card}> 
         <CardTitle title={'Sponsored'}/> 
         <BannerView 
          placementId={placementId} 
          type="large" 
          style={{width: 100}} 
          onPress={() => console.log('click')} 
          onError={this.onBannerAdError} 
         /> 
        </Card> 
       </View> 
       : null); 
     default: 
      return null; 
    } 
}; 

      <View style={styles.view}> 
        <FlatList 
         data={this.state.labels} 
         keyExtractor={this._keyExtractor} 
         renderItem={this._renderItem} 
         onScroll={this._onScroll} 
         refreshing={this.state.refreshing} 
         onRefresh={this.handleRefresh} 
         onEndReached={this.handleLoadMore} 
         onEndReachedThreshold={0.1} 
         onMomentumScrollBegin={() => { 
          this.onEndReachedCalledDuringMomentum = false; 
         }} 
         removeClippedSubviews={true} 
         ListFooterComponent={this.renderFooter} 
        /> 
       </View> 
      </View> 

一切工作正常,廣告,顯示所有20個項目,但RN抱怨關鍵Warning: Each child in an array or iterator should have a unique "key" prop.

肯定有一些與「廣告」類型的主要事情,我是什麼?做錯了?如何讓「廣告」類型的關鍵字獨一無二?我嘗試了幾種方法,通過添加shortid.generate() npm模塊並在推入this.state.labels.push({key: shortid.generate(), type: 'ad'})之類的陣列時插入一個密鑰,然後在Card組件中設置key={item.key},但根本沒有運氣。

回答

1

請確保item._id對每個項目都是唯一的。

+0

在'label'的情況下,每個item._id都是唯一的,問題是,如何在'ad'情況下設置唯一的ID?正如問題中所解釋的,我試圖設置一個唯一的ID,但沒有運氣,這就像獨特的ID總是相同的,我不明白爲什麼會發生這種情況。 –

0

如果你有modulusCount/modCount的,你就不能有這樣的事情

`${modulusCount}_key` 

關鍵?

+0

試過,發生同樣的事情... –

0

看來,我用的是keyExtractor支撐走錯了路,我用_keyExtractor = (item, index) => item.id,我把它改成_keyExtractor = (item, index) => index;,除去從兩個卡key={}道具裏面_renderItem卡組件和它的作品像它應該。