【发布时间】:2021-09-25 22:33:07
【问题描述】:
我成功地获取了一个对象的数据,我正在尝试将它分配给状态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;
你知道为什么吗?
谢谢
【问题讨论】:
-
获取请求是异步的。您在获取完成之前记录它。
-
fetch是异步的。您正在尝试记录尚不存在的状态值。 -
观看此视频以更好地了解异步行为:youtube.com/watch?v=8aGhZQkoFbQ
-
谢谢!但是,当我尝试在组件内使用
{movie.title}时,我收到错误Object is possibly 'undefined'
标签: javascript reactjs typescript api fetch