【问题标题】:while running the react native app i got the error : Encountered two children with the same key在运行 react native 应用程序时出现错误:遇到两个具有相同密钥的孩子
【发布时间】:2021-10-28 11:07:15
【问题描述】:

我在两个不同的组件中使用相同的代码。我在反应本机代码中遇到错误遇到两个具有相同密钥的孩子29270。密钥应该是唯一的,以便组件在更新时保持其身份。非唯一键可能会导致子项被复制和/或省略——这种行为不受支持,并且可能在未来的版本中发生变化。 我该如何解决这个错误我不明白错误是什么以及为什么会发生请帮助我解决问题


<SafeAreaView style={styles.container}>
                    <FlatList data={this.state.dataSource}
                        renderItem={({item}) => 
                            <TouchableOpacity style={styles.item} onPress= {() =>this.props.navigation.replace('Test', { StudentUid: item1.uniquecode,  AccessToken: this.state.accessToken })} >
                                <Text style={{fontSize:16, fontWeight:'bold'}}>{item.id} {item.firstname} {item.middlename} {item1.lastname}</Text>
                            </TouchableOpacity>
                        }
                    />
                </SafeAreaView>

can  I use like this 

<SafeAreaView style={styles.container}>
                    <FlatList data={this.state.dataSource}
                        renderItem={({item}) => 
                            <TouchableOpacity key={item.id} style={styles.item} onPress= {() =>this.props.navigation.replace('Test', { StudentUid: item1.uniquecode,  AccessToken: this.state.accessToken })} >
                                <Text style={{fontSize:16, fontWeight:'bold'}}>{item.id} {item.firstname} {item.middlename} {item1.lastname}</Text>
                            </TouchableOpacity>
                        }
                    />
                </SafeAreaView> 
Is this write code?

【问题讨论】:

  • 我想你会发现更多here
  • 我找不到解决办法,请帮帮我

标签: reactjs react-native


【解决方案1】:

你有两个选择:

  1. 为您的孩子提供钥匙TouchableOpacitykey={item.id}
  2. 像这样创建一个 keyExtractor 函数
    const keyExtractor = (item) => {
      return item.id.toString();
    };

并在您的Flatlist 中使用keyExtractor={keyExtractor} 定义此函数

【讨论】:

  • 你能用我的代码解释一下吗?使用第一个选项。
  • 嗯,解决方案 1 是您只需添加到您的 TouchableOpacity 的代码,用于解决方案 2 我需要您的整个代码,但如果您查看 Flatlist 的文档,我认为这是不言自明的
  • this.props.navigation.replace('Test', { StudentUid: item1.uniquecode, AccessToken: this.state.accessToken })} > 是这个写的
  • 我已经编辑了我的问题,请检查一下。
猜你喜欢
  • 2017-05-23
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
相关资源
最近更新 更多