首页 > 解决方案 > 为什么我会收到一条警告说“列表中的每个孩子都应该有一个唯一的 key prop”,但我已经有一个子组件的唯一 key prop

问题描述

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

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

我尝试将 (argument, index) 添加到我正在使用的 map 函数中,但我收到一个错误,即未定义子组件。

//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;

标签: reactjs

解决方案


将渲染部分替换为:

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

推荐阅读