React 组件警告:列表中的每个子项都应该有一个唯一的“key”属性

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

我是 React 新手,我一直在做简单的练习。所以我想知道它给了我标题的错误。 这是我的代码:

const MovieItem = (movieData) => {


return(
    <div>
      {Object.entries(movieData).map((values)=>{
        return <li key={values.id}>{values.title}</li> 
      })} 
    </div> 
  )
}

export default MovieItem

这是一个名为 MovieItem 的文件夹内部,就像组件一样,App 内部如下:

    function App() {
  const [movies, setMovies] = useState([
    {
      "id": "a4e4a6c7-36d3-4a3a-b2e9-3c5e6b368730",
      "title": "Inception",
      "description": "A thief who enters the dreams of others to steal their deepest secrets.",
      "year": 2010
    },
    {
      "id": "95ccff67-9097-4a9e-9e79-0253b4f59ddc",
      "title": "The Shawshank Redemption",
      "description": "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
      "year": 1994
    },
    {
      "id": "f21a43a7-64a1-40f7-a4ed-c04b28a9bf4b",
      "title": "The Godfather",
      "description": "The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.",
      "year": 1972
    },
    {
      "id": "4b9467a0-2244-4ae1-9d44-5201b4e8e56a",
      "title": "Goodfellas",
      "description": "The story of Henry Hill and his life in the mob, covering his relationship with his wife Karen Hill and his mob partners Jimmy Conway and Tommy DeVito.",
      "year": 1990
    }
  ])
    
  return(
    <div>
      <ol>
        {movies.map((movies) =>{
          return <MovieItem id={movies.id} title={movies.title} description={movies.description} year={movies.year} set={movies.set}/>
        })}
      </ol>
    </div>
  )
}

export default App

有什么问题吗?

reactjs key
1个回答
-1
投票
    const MovieItem = (movieData) => {
return(
    <div>
      {Object.entries(movieData).map((values, index)=>{
        return <li key={index}>{values.title}</li> 
      })} 
    </div> 
  )
}

export default MovieItem

这将解决您的问题。 始终使用唯一键作为映射的键。否则,DOM 无法识别或标识该组件。这就是为什么会出现这个错误

© www.soinside.com 2019 - 2024. All rights reserved.