【发布时间】: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