【问题标题】:"Warning: Each child in a list should have a unique "key" prop" in React (TypeScript)“警告:列表中的每个子项在 React (TypeScript) 中都应该有一个唯一的“键”道具”
【发布时间】:2021-10-05 20:05:45
【问题描述】:

在 React (TypeScript) 中我得到:

警告:列表中的每个孩子都应该有一个唯一的“key”道具。查看 MyCollection的渲染方法

这是MyCollection

export default function MyCollection(props:any ) {
  let nodes = useSelector((state: any) => state.vpms.norm.nodes);
  // let node = useSelector((state: any) => state.vpms.norm.nodes[props.id]);
  const groupListAdapter: GroupListAdapter = useGroupList(props);
  let items: any = [];
  groupListAdapter.itemsIds().forEach((itemId:any) => {items.push(nodes[itemId])});

  return (
    <>
      {items.map(props.render)}
    </>
  );
}

这就是它在父组件中的调用方式:

export default function App() {
...

const id = (node: any, name: string) => nodes[node.c[name]].id;

return (
{iter(root, 'persons').map((persons: any, index: number) => { return (
<MyCollection id={id(persons, 'coverages')} 
    render= {(coverages: any, index: number) => (
        <Accordion id={coverages.id} isExpanded={true}  >
        <Grid columns={4} style={{width: "100%"}} >
         ....../>
...
)

如何获得唯一密钥以避免出现此警告?请注意,App 中的 id 属性是 MyCollection 中所有 items 的单个 id。

【问题讨论】:

  • coverages 中有哪些字段可用?如果那里有什么独特的东西,那可能就是关键。
  • 您省略了此问题代码中最重要的部分:render={(coverages: any, index: number) =&gt; (..... 点中的部分需要生成包含key 标记的组件。

标签: reactjs typescript


【解决方案1】:

这样映射的时候可以得到item的索引

yourArray.map((item, itemIndex) => <SomeComponent key={itemIndex} />);

虽然您确实应该为每个项目设置一个唯一标识符。因为它在 React 中被视为反模式

更多信息在这里:

【讨论】:

    【解决方案2】:

    您可以在映射时使用索引作为键:

    list.map((item,index)=>{
    return (
    <p key={index}>Samle Text</p>
    )
    })
    

    【讨论】:

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