首页 > 解决方案 > 即使表格行上有唯一键,唯一键道具错误

问题描述

我不知道如何纠正这个问题。我正在使用唯一 ID,但反应仍然不高兴。我试图在每个上都这样做,但后来它抱怨重复。

          <table>
            <tbody>
              {!loading &&
                products &&
                products.map((product) => (
                  <>
                    <tr>
                      <td key={product._id}>{product.name}</td>
                      <td>
                        <span>
                          <strong>{product.desc}</strong>
                        </span>
                      </td>
                    </tr>
                  </>
                ))}
            </tbody>
          </table>

标签: reactjs

解决方案


或者与其自己处理密钥,不如让 React 为您处理。我觉得它很方便:

<table>
  <tbody>
    {
      !loading && products && React.Children.toArray(
        products.map((product) => (
          <tr>
            <td>{product.name}</td>
            <td>
              <span>
                <strong>{product.desc}</strong>
              </span>
            </td>
          </tr>
        ))
      )
    }
  </tbody>
</table>

所以你再也不用担心分配键了!


React.Children.toArray

以平面数组的形式返回子级不透明数据结构,并为每个子级分配键。如果你想在你的渲染方法中操作孩子的集合,特别是如果你想在传递它之前重新排序或切片 this.props.children 时很有用。

官方文档:https ://reactjs.org/docs/react-api.html#reactchildrentoarray


推荐阅读