【问题标题】:Why do I get a warning that says " each child in a list should have a unique key prop" but I already have a unique key prop for the child component为什么我会收到一条警告说“列表中的每个孩子都应该有一个唯一的键道具”,但我已经有一个子组件的唯一键道具
【发布时间】:2019-10-12 01:21:42
【问题描述】:

我对在线课程做出反应并编写代码是新手。我收到一个警告,列表中的每个孩子都应该有一个唯一的关键道具。然而,子组件已经有一个唯一的 key prop。

当按下增量按钮时,程序应该增加一个对象值的值,在这种情况下 counter.value 加一,但我得到一个键错误。

我已尝试将(参数,索引)添加到我正在使用的地图函数中,但我收到一个错误,即未定义子组件。

//Parent Component

import React, { Component } from "react";
import Counter from "./counter";

class Counters extends Component {
  state = {
    counters: [
      { id: 1, value: 9 },
     ]
  };

  handleIncrement = counter => {
    const counters = [...this.state.counters];
    const index = counters.indexOf(counter);
    counters[index] = { ...counters };
    counters[index].value++;
    this.setState({ counters });
  };


   render() {
    return (
      <div>

        {this.state.counters.map(counter => (
          <Counter
            key={counter.id}
            onIncrement={this.handleIncrement}

          />
        ))}
      </div>
    );
  }
}

export default Counters;

//Child Component
import React, { Component } from "react";

class Counter extends Component {
   return (
      <div>

        <button
          onClick={() => this.props.onIncrement(this.props.counter)}

        >
          Increment
       </button>

}

export default Counter;

【问题讨论】:

  • 语法错误,缺少一些花括号 --> key={counter.id}
  • Jayce444,你可以写在答案部分。

标签: reactjs


【解决方案1】:

将渲染部分替换为:

 render() {
    const { counters } = this.state;
    return (
      <div>
        {counters.map(counter => {
            const counterKey = `counter-${counter.id}`;
            return (
                <Counter
                  key={counterKey}
                  onIncrement={this.handleIncrement}
                />
            )})
        }
      </div>
    );
  }

【讨论】:

  • 为什么不使用key={counter.id}
  • 我重新输入了 handleIncrement 方法,它现在可以工作了。我不确定发生了什么变化。
猜你喜欢
  • 2021-11-29
  • 2023-02-17
  • 2021-09-01
  • 2020-05-09
  • 2019-08-04
  • 2021-01-12
  • 2022-06-28
  • 2021-11-17
  • 2019-12-05
相关资源
最近更新 更多