获取的对象未分配给 React 状态

Fetched object is not assigned to React state

我成功地获取了一个对象的数据,我正在尝试将它分配给状态 movie。但是,当我安慰它时,它的值是 undefined.

import React, {useState, useEffect} from "react";
import Topbar from '../Header/Topbar';

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

interface Movie {
  id: number;
  title: string;
  rating: number;
  description: string;
  picture?: string;
  date: string;
}

const MoviePage = (props: any) => {

const [movie, setMovie] = useState<Movie>();

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 {};
    });


  console.log('movie ', movie); // HERE IT CONSOLES OUT undefined

}, [currentMovieId, movie]);


  return (
    <React.Fragment>
        <Topbar></Topbar>
        <div>
          Here fetched data will be displayed
        </div>
    </React.Fragment>
  );
}

export default MoviePage;

你知道为什么吗?

谢谢

使用新效果访问它以查看状态更新,因为状态更新是异步的

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]);


//access it with a new effect to see the state update since state update is asynchronus
useEffect(() => {

  console.log("::Movie::", movie)


}, [movie]);