react错误:警告:列表中的每个孩子都应该有一个唯一的“键”props

IT技术 reactjs jsx
2021-05-05 09:01:54

我收到以下错误:

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>
  )
}
4个回答

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

countries.map(({country, cases}) => {
  <tr key={country}>
     <td>{country}</td>
     <td>
       <strong>{cases}</strong>
     </td>
  </tr>
})

只要国家/地区名称是唯一的,就可以了。您可能希望使用类似简短格式的ISO 国家/地区代码来避免重音和拼写的混乱。

首先,您没有返回迭代国家/地区的元素。如果你没有为你在循环中渲染的每个元素提供键,React 会抛出一个警告。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>
    );
}

React 要求你需要有一个keyprop 来区分循环中的元素

function Table({ countries }) {
  return (
    <div className="table">
      {countries.map(({ country, cases }) => {
        <tr key={country}>
        <!-- or key={Date.now()}, if your countries are not unique -->
          <td>{country}</td>
          <td>
            <strong>{cases}</strong>
          </td>
        </tr>
      })}
    </div>
  )
}

警告:

警告:列表中的每个孩子都应该有一个唯一的“key”props。

告诉你你没有为你使用的列表提供唯一的键props.map

键可以是任何本地唯一值。在文档中阅读更多内容

下面是几个例子:

// wrong
<div>
{
  [1,2,3,4,5].map(num => <p>{num}</p>)
}

// Correct. Good.
{
  [1,2,3,4,5].map(num => <p key={num}>{num}</p>)
}

// Correct. Not so good.
{
  [1,2,3,4,5].map((num, index) => <p key={index}>{num}</p>)
}

// Correct. Bad.
{
  [1,2,3,4,5].map((num) => <p key={Math.random()}>{num}</p>)
}

// Wrong
{
  [1,2,3,4,4,4].map((num) => <p key={num}>{num}</p>)
}

// Correct
{
  [1,2,3,4,4,4].map((num, index) => <p key={index}>{num}</p>)
}
</div>

因此,要修复您的代码:

{countries.map(({ country, cases }) => {
  return <tr key={SOME_KEY_HERE}> { /* Maybe, key={country} or key={countryID} */ }
    <td>{country}</td>
    <td>
      <strong>{cases}</strong>
    </td>
  </tr>
})}