反应错误:警告:列表中的每个子代都应具有唯一的“键".支柱 [英] React Error: Warning: Each child in a list should have a unique "key" prop

查看:61
本文介绍了反应错误:警告:列表中的每个子代都应具有唯一的“键".支柱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下错误:

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

这是我的代码:

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

推荐答案

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

First of all you are not returning element iterating the countries. React throws an warning if you do not provide key for each element you render within the loop as. Key is needed for react to identify which element has been changed. You can pass index to the key as the country or the cases can be same.

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>
    );
}

这篇关于反应错误:警告:列表中的每个子代都应具有唯一的“键".支柱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆