[英]Use Updated API data(From UseEffect) to Update Another State Value
I have an application that gets movie information from an API as an array using the UseEffect hook and stores the response in state ( movies ), I also have a function ( getIndexMovie ) that gets a random movie object from the stored array of movies and stores the returned object in another state ( selectedMovie ). I have an application that gets movie information from an API as an array using the UseEffect hook and stores the response in state ( movies ), I also have a function ( getIndexMovie ) that gets a random movie object from the stored array of movies and stores在另一个 state ( selectedMovie ) 中返回 object。 I would like to display a random movie information whenever the page loads, how can I achieve this?
我想在页面加载时显示随机电影信息,我该如何实现?
I tried this:我试过这个:
const [movies, setMovies] = useState<TrendingMovieResultModel[]>([]);
const [selectedMovie, setSelectedMovie] = useState<SelectedMovieModel>({
"backdrop_path": "",
"title": "",
"original_language": "",
"original_title": "",
"poster_path": "",
"video": false,
"vote_average": 0,
"vote_count": 0,
"overview": "",
"release_date": "",
"id": 0
});
useEffect(() => {
fetch(`${baseUrl}trending/all/day?api_key=${API_KEY}`)
.then(response => response.json())
.then(data => {
setMovies(data.results);
}).catch(err => console.log(err));
}, []);
const getRand = (max: number) => {
return Math.floor(Math.random() * max);
}
//where can i call this function ?
const getIndexMovie = () => {
const randomIndex = getRand(movies.length);
const {
title, backdrop_path, original_language, original_title, poster_path,
video, vote_average, vote_count, overview, release_date,
id
} = movies[randomIndex];
setSelectedMovie({ backdrop_path, title, original_language, original_title,
poster_path, video, vote_average, vote_count, overview, release_date, id
});
}
You could do that by adding it to your useEffect
hook.你可以通过将它添加到你的
useEffect
钩子来做到这一点。
useEffect(() => {
fetch(`${baseUrl}trending/all/day?api_key=${API_KEY}`)
.then(response => response.json())
.then(data => {
setMovies(data.results);
const randIndex = getRand(data.results.length);
setSelectedMovie(data.results[randIndex]);
}).catch(err => console.log(err));
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.