在 ReactJS 中拉取嵌套的 URL 端点

Pulling nested URL endpoints in ReactJS

我一直在玩星球大战 API,但我很难从角色 (https://swapi.dev/api/people/1/) 中提取电影数据。

export const SwapiFilms = (props) => {
  const [films, setFilms] = useState([]);

  const filmList = props.filmsUrl;

  useEffect(() => {
    function getData() {
      try {
        const response = Promise.all(
          filmList.map((url) => 
            fetch(url).then((res) => res.json())
          )
        );
        console.log(response);
        setFilms(response);
      } catch (error) {
        console.log(error);
      }
    }

    getData();
  }, []);

  return (
    <>
      Title: {films.title}
      <br />
      <br />
      Director: {films.director}
      <br />
      <br />
      {JSON.stringify(films)}
    </>
  );
};

你应该 await Promise.all

useEffect(() => {
  async function getData() { // <-- declare getData an async function
    try {
      const response = await Promise.all( // <-- await promise resolution
        filmList.map((url) => 
          fetch(url).then((res) => res.json())
        )
      );
      console.log(response);
      setFilms(response);
    } catch (error) {
      console.log(error);
    }
  }

  getData();
}, []);

您可能也不应该混合使用 promise 链和 async/await。坚持其中一个

承诺链

useEffect(() => {
  Promise.all(filmList.map(fetch))
    .then(responses => {
      if (!response.ok) {
        throw Error('Film response not ok!');
      }
      return response.json();
    })
    .then(films => {
      console.log(films);
      setFilms(films);
    })
    .catch(error => console.log(error));
}, []);

Async/Await

useEffect(() => {
  async function getData() {
    try {
      const responses = await Promise.all(filmList.map(fetch));
      const films = await Promise.all(responses.map(res => res.json());

      console.log(films);
      setFilms(films);
    } catch (error) {
      console.log(error);
    }
  }

  getData();
}, []);

旁注:您的电影状态是一个数组,因此您需要在渲染中使用数组方法访问films return.