簡體   English   中英

為什么我會收到一條警告,上面寫着“列表中的每個孩子都應該有一個獨特的關鍵道具”,但我已經為子組件提供了一個獨特的關鍵道具

[英]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

我是新手,在網上課程上做出反應並做代碼。 我得到一個警告,列表上的每個孩子應該有一個獨特的關鍵道具。 然而,子組件已經具有唯一的關鍵支柱。

程序應該增加一個對象值的值,在這種情況下,當按下增量按鈕但是我得到一個鍵錯誤時,counter.value為1。

我已經嘗試將(參數,索引)添加到我正在使用的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;

用以下內容替換渲染部分:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM