【问题标题】:Warning - Each child in a list should have a unique "key" prop警告 - 列表中的每个孩子都应该有一个唯一的“关键”道具
【发布时间】:2021-01-12 20:26:34
【问题描述】:

得到一个警告:列表中的每个孩子都应该有一个唯一的“key”道具。我不知道我需要使用哪个键。

<td className="banana-td">
                    {todos.map((todo, index) => (
                        <BananaBullet
                            key={index.id}
                            value={todo.date}
                            completed={todo.completed}
                            onClick={() => 
           toggleTodo(todo.id)}
                        />
                    ))}
                </td>

                <td className="task-td">
                    {todos.map((todo, index) => (
                        <TodoContainer
                            key={index.id}
                            text={todo.text}
                            completed={todo.completed}
                            toggleTodoItem={() => 
          toggleTodo(todo.id)}
                        />
                    ))}
                </td>
                <td>
                    {todos.map((todo, index) => (
                        <DeadlineList
                            key={index.id}
                            value={todo.date}
                            completed={todo.completed}
                            onClick={() => 
                 toggleTodo(todo.id)}

我标记了react guidelines,但这并不能帮助我理解如何在我的情况下使用它

【问题讨论】:

标签: reactjs key parent-child


【解决方案1】:

index 是一个数字,而不是一个对象。只需index 就足够了。

key={index}

【讨论】:

    【解决方案2】:

    在您的代码中,您提到了:

    key={index.id}
    

    这不起作用,因为key 是一个数字/整数。您需要做的就是:

    key={index}
    

    如果我明白你想要做什么,那么你应该这样做:

    key={todos[index].id}
    

    【讨论】:

      【解决方案3】:

      看起来您的todo 对象上有一个唯一字段(id),因此您可以输入todo.id 作为键。这比使用索引值要好得多,因为 React 可能会在状态更新期间与排序混淆。为BananaBulletTodoContainerDeadlineList 执行此操作。例如:

      <BananaBullet
        key={todo.id} // change here
        value={todo.date}
        completed={todo.completed}
        onClick={() => toggleTodo(todo.id)}
      />
      

      【讨论】:

        猜你喜欢
        • 2019-08-04
        • 2022-06-28
        • 2023-02-17
        • 2019-12-05
        • 2021-09-05
        • 2020-03-01
        • 1970-01-01
        • 2020-03-27
        • 2021-04-25
        相关资源
        最近更新 更多