【问题标题】:ReactNative Warning: Each child in a list should have a unique "key" propReactNative 警告:列表中的每个孩子都应该有一个唯一的“关键”道具
【发布时间】:2019-12-05 13:44:28
【问题描述】:

我是 react-native 的新手,我正在编写一个包含卡片的应用平面列表,但出现此错误 这是我的代码

          constructor (props) {
        super(props);
        this.state = {
            GridListItems: [ // Home Screen Cards Data [STATIC]
              { id: 1 , key: "222" , img: 'https://i.ibb.co/Lt88dTg/makeup.png' },
               { id: 2 ,key: "2" , img: 'https://i.ibb.co/H4NRnZK/Photographers.png'},
               { id: 3 ,key: "Wedding Halls" , img: 'https://i.ibb.co/b2JdtHW/wedding-Hall.png'},
               { id: 4 ,key: "Wedding Planners" , img: 'https://i.ibb.co/g95HhKT/image-1.jpg'},
               { id: 5 ,key: "Ateliers for Dresses" , img: 'https://i.ibb.co/g4ksBDk/wedding.png'},
            ]
        };
    }
    renderItem = ({item}) => {
      return(
        <TouchableOpacity key={item.id.toString()}
        style={styles.GridViewContainer}
    >
      </TouchableOpacity>
      )

    }
render () {
  const carousel = this.mainCarousel(1); // Rendering the Carousel 

  return (
     <SafeAreaView style={styles.safeArea}>

    { this.gradient }
    <ScrollView
      style={styles.scrollview}
      scrollEventThrottle={200}
      directionalLockEnabled={true}
    >
        {/* { carousel }  */}

        <FlatList

        data={ this.state.GridListItems }
        keyExtractor={(item) => item.id.toString()}
        renderItem={ this.renderItem }
        numColumns={2}
        initialNumToRender={6}
/>
    </ScrollView>

</SafeAreaView>

);
}

但我收到警告:列表中的每个孩子都应该有一个唯一的“关键”道具。有关更多信息,请参阅https://fb.me/react-warning-keys。%s,

我在这里做错了什么?

【问题讨论】:

  • 我认为您发布了错误的组件部分。你在渲染函数中有.map() 或任何其他迭代函数吗?警告应该告诉您哪个组件导致了问题
  • 不,我没有 .map() 或者这里的任何东西都是项目 github 存储库,你能看到有什么问题吗,这真的很令人费解:D github.com/Ov3rControl/Weddi

标签: reactjs react-native


【解决方案1】:

检查这是否解决了问题:keyExtractor={({item, index}) =&gt; item.id.toString()} 如果不 , 改用这个: keyExtractor={(item, index) =&gt;${index}} 或

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

【讨论】:

  • 我不确定这是否解决了真正的问题。如果发布者认为他的 id 是唯一的,那么可能还有另一个问题。可能某些 id 重复或未定义,或者同一项目在列表中出现两次。
  • keyExtractor={({item, index}) => item.id.toString()} Get me undefined item.id 其余的都不好用
【解决方案2】:

我会在 keyExtractor 中创建一个 console.log 语句来看看你得到了什么:

keyExtractor={(item, index) => {
  console.log('item', item);
  return item.id.toString();
}}

通过这种方式,您可以查看传递给函数的数据并返回相关部分。

顺便说一句:Flatlist 是一个可滚动的列表,所以你不需要将它包装在 ScrollView 中。见https://facebook.github.io/react-native/docs/flatlist

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 2021-01-12
    • 2022-06-28
    • 2023-02-17
    • 2021-09-05
    • 2020-03-01
    • 1970-01-01
    • 2020-03-27
    • 2021-04-25
    相关资源
    最近更新 更多