首页 > 解决方案 > 有一种方法可以解决“警告:列表中的每个孩子都应该有一个唯一的“键”?

问题描述

有没有办法解决这个警告?

警告:列表中的每个孩子都应该有一个唯一的“键

我每次都收到此警告,但不知道如何解决。我试图修复它,但我意识到我的方式有问题。希望了解什么是错的,因为它太烦人了。

import React, { Component } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, Platform, FlatList, Dimensions, Image } from 'react-native';
import { HeaderButtons, Item } from 'react-navigation-header-buttons'
import HeaderButton from '../components/HeaderButton';
import axios from 'axios';


const { width, height } = Dimensions.get('window');

export default class PlacesListScreen extends Component {
    constructor(props) {
        super(props);
        this.state = { isLoading: true, data: [] };
    }

    componentDidMount() {
        axios.get('https://rallycoding.herokuapp.com/api/music_albums')
            .then(res => {
                this.setState({
                    isLoading: false,
                    data: res.data,
                })
                console.log(res.data);
            })
    }

    renderItem(item) {
        const { title, artist } = item.item;
        return (
            <View style={styles.itemView}>
                <View style={styles.imgContainer}>
                    {/* <Image style={styles.imageStyle}
                        source={{ uri: image }}
                    /> */}
                </View>

                <View style={styles.itemInfo}>
                    <Text style={styles.name}>
                        {title+ ' ' + artist}
                    </Text>
                    <Text style={styles.vertical} numberOfLines={1}>{title} |</Text>
                </View>
            </View>
        );
    }

    render() {
        if (this.state.isLoading) {
            return (
                <View style={{ flex: 1, padding: 20 }}>
                    <Text style={{ alignSelf: 'center', fontWeight: 'bold', fontSize: 20 }}>loading...</Text>
                    <ActivityIndicator />
                </View>
            )
        }


        return (
                <View style={styles.container}>
                    <FlatList
                        data={this.state.data}
                        renderItem={this.renderItem.bind(this)}
                        keyExtractor={item => item.id}
                    />
                </View>
            );
        }
    }

希望您了解我的问题以及我该如何解决。上面的示例代码显示了我尝试从 API 获取一些数据,但它每次都会返回一个警告,关于列表中的每个孩子都应该有一个唯一的“键”。

标签: javascriptreact-nativeaxiosexporeact-native-flatlist

解决方案


console.log 每个项目的键。您可能对某些项目有相同的 id 吗?


推荐阅读