【问题标题】:Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of 'search'警告:数组或迭代器中的每个孩子都应该有一个唯一的“key”道具。检查“搜索”的渲染方法
【发布时间】:2019-05-01 14:17:49
【问题描述】:

搜索很完美,一切看起来都很好,但收到了这个警告。
当我按任意键启动搜索方法时,我收到此警告。
“Song_ID”、“Song_Name”和“Image”是 SQL 数据库中的变量名。
- 我把其他问题看作是这样,但它根本没有帮助我。
这是错误所在的代码:

return (
        <View>
          <ScrollView>
            {musicList.map(songObj => {
              return (
                <View style={styles.resultsContainer}> /// Its written that the erorr in this line
                  <TouchableOpacity onPress={this.GetListViewItem.bind(this, songObj.Song_Name)}>
                  <Text style={{ fontSize: 16 }} key={songObj.Song_ID}>
                  {songObj.Song_Name}</Text>
                    <Image source={{ uri: songObj.Image }} style={styles.img} />
                  </TouchableOpacity>
                </View>
              );
            })}
          </ScrollView>
        </View>
      );
    }

我不明白把钥匙放在哪里和/或它是什么意思,我试了很多次,但效果不佳。
如果需要更多详细信息,请告诉我,我'将插入正确的代码。

【问题讨论】:

标签: javascript reactjs react-native view


【解决方案1】:

您应该将密钥添加到map 内的最外层组件上。在您的情况下,这是View。试试这个:

return (
        <View>
          <ScrollView>
            {musicList.map(songObj => {
              return (
                <View style={styles.resultsContainer} key={songObj.Song_ID}>
                  <TouchableOpacity onPress={this.GetListViewItem.bind(this, songObj.Song_Name)}>
                  <Text style={{ fontSize: 16 }}>
                  {songObj.Song_Name}</Text>
                    <Image source={{ uri: songObj.Image }} style={styles.img} />
                  </TouchableOpacity>
                </View>
              );
            })}
          </ScrollView>
        </View>
      );
    }

添加 key 属性可以让 react 优化渲染,这就是它建议您添加它的原因。阅读the docs了解更多信息。

【讨论】:

    猜你喜欢
    • 2018-12-17
    • 2016-12-07
    • 2017-05-02
    • 2018-11-09
    • 2023-02-22
    • 2018-04-29
    • 2018-05-22
    • 2017-02-23
    • 2017-02-03
    相关资源
    最近更新 更多