簡體   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