尽管所有元素都有唯一标识符,但仍对键错误做出反应

问题描述 投票:0回答:2

所以我正在习惯React,并且我理解在使用map函数时每个项目都需要分配一个唯一的键。我相信我这样做是正确的

    return (
     countries.map(country => {
        return <>
        <div key={country.name.common}>
            {country.name.common} <button onClick={() => setCountries([country])}>show</button>
        </div>
        </>
      })
   )

我仍然在控制台中收到错误消息:

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

在国家/地区列表。

在div。

CountryList 是从中提取代码的文件。我尝试向按钮元素添加相同的键,并尝试为按钮元素提供自己的唯一键。

descriptive key error message

countries 是对“https://restcountries.com/v3.1/all”api 的调用。

useEffect(() => {
    axios.get("https://restcountries.com/v3.1/all")
         .then(response => setCountries(response.data))
  }, [])
const handleFilterChange = (event) => {
    setFilter(event.target.value)
    const filtered = countries.filter(country => country.name.common.toLowerCase().includes(event.target.value))
    setCountries(filtered)
  }

console error message along with what the app looks like

javascript reactjs
2个回答
2
投票

键必须放置在您从地图函数返回的父元素上。
由于在本例中它是一个片段,因此您不能直接为其分配键,除非您使用实际的 fragment 组件

// Can't assign a key
<></>
// Can assign a key
<React.Fragment key={...}></React.Fragment>

话又说回来,如果这里只有

div
,为什么还需要片段?
代码的较短语法如下所示:

return (
   countries.map(country => (
      <div key={country.name.common}>
         {country.name.common}
         <button onClick={() => setCountries([country])}>show</button>
      </div>
   ))
)

1
投票

您正在使用

<>
作为父标签,并在子
<div>
标签中添加键,删除
<></>
,因为您不需要它或使用
Fragment
代替

  return countries.map(country => (
    <div key={country.name.common}>
      {country.name.common}
      <button onClick={() => setCountries([country])}>show</button>
    </div>
  ))

return countries.map(country => {
  return (
    <React.Fragment key={country.name.common}>
      <div>
        {country.name.common} <button onClick={() => setCountries([country])}>show</button>
      </div>
    </React.Fragment>
  )
})
© www.soinside.com 2019 - 2024. All rights reserved.