繁体   English   中英

如何将获取的数据分配给 React 状态

[英]How to assign fetched data to React state

我试图获取一个对象的数据(在这个例子中来自https://api.themoviedb.org/3/movie/459151?api_key=f13446aa3541ebd88cf65b91f6932c5b ),我试图将它分配给 state 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;

如何解决? 谢谢

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

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

您必须将.then((res) => setMovie(res.results)) .then((res) => 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]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM