【问题标题】:How to fix 'Each child in a list should have a unique "key" prop.'如何解决“列表中的每个孩子都应该有一个唯一的“关键”道具。
【发布时间】:2019-07-23 18:12:16
【问题描述】:

我正在从 JSON api 中提取数据。我在 map 函数生成的唯一元素中分配了一个键,但我不知道为什么我仍然看到这个警告。我需要在哪里分配密钥?

import React from 'react';
import PokeCell from './PokeCell';
import './styles/PokeList.css';

const PokeList = (props) => {

return (
    <section className="poke-list">
        {props.pokemon.map((pokemon) => (
            <PokeCell 
                key={pokemon.id}
                id={pokemon.id}
                name={pokemon.name}
                image={pokemon.image}
            />
         ))}
    </section>
 )
}

export default PokeList;

index.js:1375 Warning: Each child in a list should have a unique "key" 
prop.

Check the render method of `PokeList`
    in PokeCell (at PokeList.js:10)
    in PokeList (at App.js:24)
    in div (at App.js:20)
    in App (at src/index.js:7)

【问题讨论】:

  • 你把钥匙放在了正确的地方......在你回电话之前你能clgprops.pokemon的ID吗?
  • pokemon.id 的值有效吗?

标签: reactjs


【解决方案1】:

您可以使用数组index 来拥有唯一键。

<section className="poke-list">
    {props.pokemon.map((pokemon, index) => (
        <PokeCell 
            key={pokemon.id + index}
            id={pokemon.id}
            name={pokemon.name}
            image={pokemon.image}
        />
     ))}
</section>

【讨论】:

  • 这成功了!非常感谢你!我猜 pokemond.id 并不像我想象的那样独特。
【解决方案2】:

您必须确保每个 id 都是唯一的,才能使 react 正确更新组件。

您不应将索引用作键值,因为从列表中删除项目或对其重新排序可能会导致错误。

您必须确保每个 id 在列表的所有可能配置(添加、删除等)中都是唯一的,以防止不必要的重新渲染。

您应该保留该实施并更改保护数据的方式以提供唯一 ID。

【讨论】:

    猜你喜欢
    • 2019-08-21
    • 2021-09-23
    • 2020-01-24
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多