这是每 20 张卡片获取项目并注入一个广告的组件代码,它使用分页,当用户到达列表底部时,卡片被添加到现有数据中:
// 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'})
,然后key={item.key}
在Card
组件中设置,但根本没有运气。