【问题标题】:How to assign fetched data to React state如何将获取的数据分配给 React 状态
【发布时间】:2021-07-17 14:09:02
【问题描述】:

我试图获取一个对象的数据(在这个例子中来自https://api.themoviedb.org/3/movie/459151?api_key=f13446aa3541ebd88cf65b91f6932c5b)并且我试图将它分配给状态movie。但是,当我将其调出时,它的值为undefined(实际上,它被调出两次,第一次使用默认状态值,第二次使用未定义值)。

import React, {useState, useEffect} from "react";
import Topbar from '../Header/Topbar';
import noImage from '../../images/no-image-available.png';

const movieApiBaseUrl = "https://api.themoviedb.org/3";

interface Movie {
  id: number;
  title: string;
  vote_average: number;
  overview: string;
  poster_path?: string;
  date: string;
}

const MoviePage = (props: any) => {

  const [movie, setMovie] = useState<Movie>(
    {
      id: 0,
      title: '',
      vote_average: 0,
      overview: '',
      poster_path: noImage,
      date: '', 
    }
  );

  const currentMovieId = window.location.pathname.split('/')[2];

useEffect(() => {
  fetch(
    `${movieApiBaseUrl}/movie/${currentMovieId}?api_key=${process.env.REACT_APP_API_KEY}`
  )
    .then((res) => res.json())
    .then((res) => setMovie(res.results))
    .catch(() => {
        return {};
    });
}, [currentMovieId, movie]);

useEffect(() => {
  // here movie is consoled out as undefined
  console.log("::Movie::", movie);
}, [movie]);

  return (
    <React.Fragment>
        <Topbar></Topbar>
        <div className="">
          MOVIE INFO HERE    
        </div>
    </React.Fragment>
  );
}

export default MoviePage;

如何解决? 谢谢

【问题讨论】:

  • 从第一个 useEffect 中删除 'movie' 作为依赖项。

标签: javascript reactjs typescript api react-hooks


【解决方案1】:

在您提供的 API 端点中,响应正文中没有 result 键。

.then((body) => setMovie(body))

【讨论】:

    【解决方案2】:

    您必须将.then((res) =&gt; setMovie(res.results)) 替换为.then((res) =&gt; setMovie(res)),因为来自响应api 的对象没有results 属性。

    顺便说一句,您应该从传递给useEffect 的数组中删除movie 属性,否则您将无限获取数据*

    useEffect(() => {
      fetch(`${movieApiBaseUrl}/movie/${currentMovieId}?api_key=${process.env.REACT_APP_API_KEY}`)
        .then((res) => res.json())
        .then((res) => setMovie(res))
        .catch(() => {});
    }, [currentMovieId]);
    

    【讨论】:

      猜你喜欢
      • 2021-04-08
      • 2021-09-25
      • 2016-03-25
      • 2018-08-29
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      相关资源
      最近更新 更多