javascript 我想在提交时获得电影列表(API)

5m1hhzi4  于 2023-08-02  发布在  Java
关注(0)|答案(2)|浏览(132)

我想在提交时获取电影列表(API),所以我使用模板文字创建了API链接,如下所示▼

  1. const getMovies = async () => {
  2. const json = await (
  3. await fetch(
  4. `https://yts.mx/api/v2/list_movies.json?minimum_rating=8&page=${Math.round(Math.random()*100)}&query_term=${movieName}&sort_by=year`
  5. )
  6. ).json();
  7. setMovies(json.data.movies);
  8. setLoading(false);
  9. };

字符串
然后,我将movieName填充到useEffect的数组中,因为每次movieName发生变化时,我都想重新获取API,但这不起作用。
有什么问题吗?
▼我写的代码

  1. import { useEffect, useRef, useState } from "react";
  2. import Movie from "../components/Movie";
  3. function Home(){
  4. const [loading, setLoading] = useState(true);
  5. const [movies, setMovies] = useState([]);
  6. const [movieSearch, setMovieSearch] = useState('');
  7. const [movieName, setMovieName] = useState('');
  8. const getMovies = async () => {
  9. const json = await (
  10. await fetch(
  11. `https://yts.mx/api/v2/list_movies.json?minimum_rating=8&page=${Math.round(Math.random()*100)}&query_term=${movieName}&sort_by=year`
  12. )
  13. ).json();
  14. setMovies(json.data.movies);
  15. setLoading(false);
  16. };
  17. const onChange = (event) =>{
  18. setMovieSearch(event.target.value)
  19. }
  20. const onSubmit = (event)=>{
  21. event.preventDefault();
  22. setMovieName(movieSearch)
  23. }
  24. useEffect(() => {
  25. getMovies();
  26. }, [movieName]);
  27. return (
  28. <>
  29. <h4>Search</h4>
  30. <form onSubmit={onSubmit}>
  31. <input
  32. onChange={onChange}
  33. type="text"
  34. value={movieSearch}
  35. placeholder="..."
  36. ></input>
  37. </form>
  38. {loading ? (
  39. <h3>Loading</h3>
  40. ) : (
  41. <div>
  42. {movies.map((item) => (
  43. <Movie
  44. key={item.id}
  45. id={item.id}
  46. title={item.title}
  47. year={item.year}
  48. medium_cover_image={item.medium_cover_image}
  49. rating={item.rating}
  50. runtime={item.runtime}
  51. genres={item.genres}
  52. summary={item.summary}
  53. />
  54. ))}
  55. </div>
  56. )}
  57. </>
  58. );
  59. }

w6lpcovy

w6lpcovy1#

为什么不尝试在设置电影名称之后将useEffect中的getMovies()移动到onSubmit()函数中呢?

plicqrtu

plicqrtu2#

因为您没有在搜索inputonChange事件上更新answerName状态
const onChange =(event)=>{ const value = event.target.value setMovieSearch(value)setMovieName(value)}

相关问题