【问题标题】:Warning: Encountered two children with the same key, `0`警告:遇到两个孩子使用相同的密钥,`0`
【发布时间】:2018-06-04 06:08:31
【问题描述】:

我正在尝试映射一个数组,并在表格项中显示我想要的内容。它要求我提供唯一键,因此我选择了以下代码,因为我在另一个组件中使用了它。我很好奇为什么它在这里不起作用。

renderData() {
   const { aminos } = this.props.aminos;
    return aminos.map((micro, i) => {
       return (
        <Table>
          <tbody>
             <tr>
              <th scope="row">1</th>
              <th key={i}>{micro.name}</th>
             </tr>
             <tr>
                <td key={i}>{micro.serum.current}</td>
                <td key={i}>{micro.serum.prev}</td>
                <td key={i}>{micro.serum.ref}</td>
             </tr>
           </tbody>
         </Table>
       )
   }

【问题讨论】:

    标签: arrays reactjs html-table key mapping


    【解决方案1】:

    键应该放在最外面的组件上。

    return aminos.map((micro, i) => {
       return (
        <Table key={i}>
          <tbody>
             <tr>
              <th scope="row">1</th>
              <th >{micro.name}</th>
             </tr>
             <tr>
                <td>{micro.serum.current}</td>
                <td>{micro.serum.prev}</td>
                <td>{micro.serum.ref}</td>
             </tr>
           </tbody>
         </Table>
       )
    }
    

    虽然这张地图会显示多个表格,但也不确定这是您想要的效果。此外,使用索引作为键也不是一个好主意,您应该使用某种唯一 id,例如数据库中的主键。

    【讨论】:

    猜你喜欢
    • 2018-10-06
    • 2017-06-01
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 2017-12-15
    • 2017-05-17
    • 2019-07-17
    • 1970-01-01
    相关资源
    最近更新 更多