1

这是每 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组件中设置,但根本没有运气。

4

3 回答 3

1

请确保 item._id 对于每个项目都是唯一的。

于 2017-09-12T10:43:24.947 回答
0

似乎我以错误的方式使用了 keyExtractor 道具,我正在使用_keyExtractor = (item, index) => item.id,我将其更改为_keyExtractor = (item, index) => index;,从 Card 组件内的两张卡中删除了key={}道具_renderItem,它的工作方式应该如此。

于 2017-09-13T09:38:41.450 回答
0

如果你有模数/模数,你不能只有类似的东西吗

`${modulusCount}_key`

作为关键?

于 2017-09-12T11:20:34.317 回答