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

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

我想在提交时获取电影列表(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>
      )}
    </>
  );
}

w6lpcovy

w6lpcovy1#

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

plicqrtu

plicqrtu2#

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

相关问题