Reactjs 警告:列表中的每个 child 都应该有一个唯一的 "key" 道具

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

我正在学习反应,我正在尝试做一个简单的程序,但我有这个错误,我找不到错误在哪里,我已经检查过,每部电影的 imdID 都不同。

要查看我正在使用的 json 文件,请参阅 https://www.omdbapi.com/

    import { useState, useEffect } from "react";
import MovieList from "./components/MovieList";

const APIKEY = "";
const URL = "https://www.omdbapi.com/";

async function fetchMovies(search = "The godfather") {
  const response = await fetch(URL + "?s=" + search + APIKEY).then((resp) =>
    resp.json()
  );
  //.then((ris) => ris);

  const { Search: movies, totalResults: totalcount } = response;

  return { movies, totalcount };
}

function App() {
  const [movies, setMovies] = useState([]);
  const [totalCount, setTotalCount] = useState(0);

  useEffect(() => {
    // fetchMovies(); se facessi così fetchMovies è asincrona
    // quindi il codice dentro use effect non si blocca

    const callApi = async () => {
      const data = await fetchMovies();

      setMovies(data.movies);
      setTotalCount(data.totalcount);
    };

    callApi();

    return () => {};
  }, []);

  return (
    <div className="App container-fluid">
      <h1>My favourite movies </h1>
      <MovieList movies={movies} />
      <button type="button" className="btn btn-primary">
        Primary
      </button>
    </div>
  );
}

export default App;



function MovieList({ movies }) {
  return (
    <ul>
      {movies.map((movie) => {
        return <li key={movie.imdID}> {movie.Title}</li>;
      })}
    </ul>
  );
}

export default MovieList;

在浏览器上代码有效,感谢您的帮助

function MovieList({ movies }) {
  return (
    <ul>
      {movies.map((movie) => {
        return <li key={movie.imdID}> {movie.Title}</li>;
      })}
    </ul>
  );
}

你打错了。它是 movie.imdbID 而不是 movie.imdID。 所以 React 会给你警告,因为所有这些 id 都被作为未定义的传递,这不是唯一的。

这是您的 API

制作的电影对象的样子
{
  "Title": "",
  "Year": "",
  "imdbID": "",
  "Type": "movie",
  "Poster": ""
}

你也可以使用 map 函数的索引来使键是唯一的:

function MovieList({ movies }) {
  return (
    <ul>
      {movies.map((movie,index) => {
        return <li key={index}> {movie.Title}</li>;
      })}
    </ul>
  );
}