为什么在我的 React-Native FlatList 中有 double 和相同的键?

Why is there double with the same key in my React-Native FlatList?

我正在尝试获取在以下端点描述的对象: https://api.cosmicjs.com/v1/67302ce0-7681-11e9-8193-4bd8888ec129/objects?pretty=true&hide_metafields=true

您会注意到有一个带有唯一标识符的 _id 字段。

那么为什么我得到:

"Warning: Encountered two children with the same key, :. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version."

这是我的 FlatList 渲染图:

render() {   
    if(this.props.dataToDisplay.objects){
        console.log(typeof(this.props.dataToDisplay.objects))
        console.log(this.props.dataToDisplay.objects)
        this.props.dataToDisplay.objects.forEach((item)=>{
            console.log(item)
        })

        return (
            <View style={[{backgroundColor: this.state.backgroundColor},styles.container]}>
                <FlatList
                    data={this.props.dataToDisplay.objects}
                    keyExtractor={(item, index)=>{item._id.toString()}}
                    renderItem={({item})=>{
                        <Text id={item._id}>{item.title}</Text>
                    }}
                />
            </View>
        );
}
 else {

    return (
        <View style={[{backgroundColor: 
this.state.backgroundColor},styles.container]}>
            <Text>Loading elements.</Text>
        </View>
      );
    }
  }
}

keyExtractor 会不会有问题? 我尝试使用 keyExtractor={(item, index)=>{item._id}} 没有结果...

感谢您的宝贵时间。

而不是 keyExtractor={(item, index)=>{item.key}} 使用 keyExtractor={(item, index)=>index.toString()}

在您的示例中,您没有任何名为 "key" 的属性,因此您有一个错误。您应该尝试分配另一个属性,如关键元素,可能是对象中存在的属性“_id”,如下所示:

<FlatList
data={this.props.dataToDisplay.objects}
keyExtractor={(item, index) => {item._id}}
numColumns={2}
renderItem={({item})=>{
  <Text id={item._id}>{item.title}</Text>
}}
/> 

keyExtractor 没问题。 return 函数不是:

keyExtractor={(item, index)=>{item._id.toString()}}

通过打开花括号 {} 引擎需要一个 return 关键字来 return 任何东西。否则它是 void

执行以下任一操作:

keyExtractor={(item, index)=> item._id.toString()}

或:

keyExtractor={(item, index)=> { return item._id.toString()}}

renderItem 方法也是如此:

renderItem={({item})=>{
           <Text id={item._id}>{item.title}</Text>
         }}

因为你打开了 {},你取消了箭头函数的隐式 return 并且你必须显式地追加它

renderItem={({item})=>{
        return <Text id={item._id}>{item.title}</Text>
         }}

顺便说一句,id 不是 <Text/> 的道具之一。如果没有 keyExtractor 函数,您将不得不自己附加 key 属性(而不是 id)。删除它是安全的 =)