【问题标题】:Each child unique "key" prop每个孩子独一无二的“钥匙”道具
【发布时间】:2019-07-25 08:01:51
【问题描述】:

我收到此警告:

警告:列表中的每个孩子都应该有一个唯一的“key”属性。

render() {
    const exercises = this.state.Exercises.map(exercise => {
      return (
        <View>
          <Text style={{ fontSize: 15 }}>Id: {exercise.Id} </Text>
          <Text style={{ fontSize: 15 }}>Ripetizioni: {exercise.Reps}</Text>
          <Text style={{ fontSize: 15 }}>Note: {exercise.Notes}</Text>
          <TouchableOpacity
            style={[styleButton.button, styleButton.buttonOK]}
            onPress={() => this.checkAttività(exercise.Id)}
          >

我该如何解决?

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    您应该将密钥传递给返回内容,例如:

        const exercises = this.state.Exercises.map(exercise => {
          return (
            <View key={`${exercise.Id}`}>
              <Text style={{ fontSize: 15 }}>Id: {exercise.Id} </Text>
              <Text style={{ fontSize: 15 }}>Ripetizioni: {exercise.Reps}</Text>
              <Text style={{ fontSize: 15 }}>Note: {exercise.Notes}</Text>
              <TouchableOpacity
                style={[styleButton.button, styleButton.buttonOK]}
                onPress={() => this.checkAttività(exercise.Id)}
              >
          )
        })
    

    编辑:反应期望键是一个字符串

    【讨论】:

    • 您应该明确密钥应该是唯一的(您的示例可以)
    【解决方案2】:

    您只需为您的View添加一个唯一键

    &lt;View key={exercise.Id}&gt;

    【讨论】:

      【解决方案3】:

      错误信息很清楚。 React 希望您为列表中的每个项目定义一个唯一的值,该值应作为 key 属性分配给每个 View 对象。

      如果你愿意,你可以在 map 循环中拉出索引并将其用作键:

      const exercises = this.state.Exercises.map((exercise, index) => {
        return (
          <View key={`view-${index}`}>
      ...
      

      请阅读下面的@JanosVinceller 评论并查看链接,这是一个很好的理由,不要执行我在此提出的建议。至少如果它是一个变化的列表。

      【讨论】:

      • 注意:我确实在对象上看到了id 属性,但认为将来有人可能需要更“通用”的版本。
      • 谢谢@JanosVinceller,之前还没有注意到这一点,非常好!
      猜你喜欢
      • 2021-08-07
      • 2022-11-25
      • 2022-11-11
      • 2018-11-10
      • 2023-01-19
      • 2021-04-26
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      相关资源
      最近更新 更多