反应错误:警告:列表中的每个子项都应该有一个唯一的“key”道具

ale*_*sen 7 jsx reactjs

我收到以下错误:

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

Check the render method of `App`. 
See https://reactjs.org/link/warning-keys for more information.
WithStyles@http://localhost:3000/static/js/vendors~main.chunk.js:39295:25
App@http://localhost:3000/static/js/main.chunk.js:197:91
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

function Table({ countries }) {
  return (
    <div className="table">
      {countries.map(({ country, cases }) => {
        <tr>
          <td>{country}</td>
          <td>
            <strong>{cases}</strong>
          </td>
        </tr>
      })}
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

tad*_*man 6

React 需要以这种方式呈现的键或任何元素。这key只是一个任意但独特的属性,因此请选择适合的属性,例如:

countries.map(({country, cases}) => {
  <tr key={country}>
     <td>{country}</td>
     <td>
       <strong>{cases}</strong>
     </td>
  </tr>
})
Run Code Online (Sandbox Code Playgroud)

只要国家名称是唯一的就可以了。您可能需要使用简短的ISO 国家/地区代码之类的内容来避免重音和拼写的混乱。


Yad*_*dab 4

首先,您不会返回迭代国家/地区的元素。如果您没有为循环中渲染的每个元素提供键,React 会抛出警告。反应需要密钥来识别哪个元素已更改。您可以将索引传递给键,因为国家/地区或情况可以相同。

Table({ countries }) {
    return (
        <div className="table">
            {
            countries.map(({country, cases}, index) => {
                    return (
                      <tr key={index}>
                        <td>{country}</td>
                        <td>
                            <strong>{cases}</strong>
                        </td>
                      </tr>
                    )
                )
            }
        </div>
    );
}
Run Code Online (Sandbox Code Playgroud)