首页 > 解决方案 > React 中选项的唯一键

问题描述

我正在尝试为表单实现一系列选项。即使我已经实现了 key prop,我仍然收到此错误:

Each child in an array should have a unique "key" prop.

这些选项取自以下选项数组:

[
  {
    "id": 1,
    "label": "Active",
    "value": "Active"
  },
  {
    "id": 2,
    "label": "Inactive",
    "value": "Inactive"
  },
  {
    "id": 3,
    "label": "Alert",
    "value": "Alert"
  }
]

下面是我的代码:

<li>
    <label className={styles.destaque}>Status</label>
    <select
      value={camposFormulario?.status}
      onChange={(event) =>
        setCamposFormulario((prev) => ({
          ...prev,
          ['status']: event.target.value,
        }))
      }
    >
      {statusList.map((option: any) => {
        return (
          <option key={option.id} value={option.value}>
            {option.label}
          </option>
        );
      })}
    </select>
  </li>

我已经阅读了这个主题:Understanding unique keys for array children in React.js,我相信我已经遵循了这些指示。

任何帮助将非常感激。
非常感谢!

编辑: 另外,如果我通过这个更改map功能,它可以工作:

<option>Ativo</option>
<option>Inativo</option>
<option>Em Alerta</option>

标签: reactjskey

解决方案


知道了。感谢Jan评论中的帮助!

由于 statusList 来自 api 调用,因此在页面首次呈现时其值为 0。那是显示错误的时候。

非常欢迎任何关于如何在 statusList 返回后呈现的建议​​!


推荐阅读