我想在提交时获取电影列表(API),所以我使用模板文字创建了API链接,如下所示▼
const getMovies = async () => {
const json = await (
await fetch(
`https://yts.mx/api/v2/list_movies.json?minimum_rating=8&page=${Math.round(Math.random()*100)}&query_term=${movieName}&sort_by=year`
)
).json();
setMovies(json.data.movies);
setLoading(false);
};
字符串
然后,我将movieName
填充到useEffect
的数组中,因为每次movieName
发生变化时,我都想重新获取API,但这不起作用。
有什么问题吗?
▼我写的代码
import { useEffect, useRef, useState } from "react";
import Movie from "../components/Movie";
function Home(){
const [loading, setLoading] = useState(true);
const [movies, setMovies] = useState([]);
const [movieSearch, setMovieSearch] = useState('');
const [movieName, setMovieName] = useState('');
const getMovies = async () => {
const json = await (
await fetch(
`https://yts.mx/api/v2/list_movies.json?minimum_rating=8&page=${Math.round(Math.random()*100)}&query_term=${movieName}&sort_by=year`
)
).json();
setMovies(json.data.movies);
setLoading(false);
};
const onChange = (event) =>{
setMovieSearch(event.target.value)
}
const onSubmit = (event)=>{
event.preventDefault();
setMovieName(movieSearch)
}
useEffect(() => {
getMovies();
}, [movieName]);
return (
<>
<h4>Search</h4>
<form onSubmit={onSubmit}>
<input
onChange={onChange}
type="text"
value={movieSearch}
placeholder="..."
></input>
</form>
{loading ? (
<h3>Loading</h3>
) : (
<div>
{movies.map((item) => (
<Movie
key={item.id}
id={item.id}
title={item.title}
year={item.year}
medium_cover_image={item.medium_cover_image}
rating={item.rating}
runtime={item.runtime}
genres={item.genres}
summary={item.summary}
/>
))}
</div>
)}
</>
);
}
型
2条答案
按热度按时间w6lpcovy1#
为什么不尝试在设置电影名称之后将useEffect中的getMovies()移动到onSubmit()函数中呢?
plicqrtu2#
因为您没有在搜索
input
的onChange
事件上更新answerName
状态const onChange =(event)=>{ const value = event.target.value setMovieSearch(value)setMovieName(value)}