简体   繁体   English

使用更新的 API 数据(来自 UseEffect)更新另一个 State 值

[英]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.

相关问题 在 useEffect 中使用 useState 值而不使 state 更新 useEffect - Use useState value in useEffect without making the state update useEffect UseEffect 不会使用更新的状态 - UseEffect won't use updated state 无法获取更新的 state 值 useState 和 UseEffect - Cannot get the updated the state value useState and UseEffect 使用 React 钩子从另一个页面使用 useEffect 更新状态 - Update state with useEffect from another page using React hooks 如何在 useReducer() 和 useContext() state 管理设置中使用 useEffect() 从 api 获取数据? - How to use useEffect() to fetch data from an api in a useReducer() and useContext() state management setup? 如何在 useEffect 之后使用更新的数据渲染组件,useEffect 从 API 获取数据 - How can I render Component with updated data after useEffect, the useEffect fetches data from an API 使用 useEffect 操作 state,但未正确渲染从更新的 state 更新 - Manipulating state with useEffect, but not correctly rendering updated from updated state 来自套接字的数据不会使用 useEffect 更新 state - Data coming in from socket doesn't update the state with useEffect State 来自 react useState 在使用 key 属性时更新,但需要 useEffect 或类似方法才能更新 - State from react useState is updated when key property is used but requires useEffect or similar method to update otherwise 在另一个提取API之后更新状态值 - Update state value after another fetch API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM