代码之家  ›  专栏  ›  技术社区  ›  RoyBarOn

如何使用react的fetch将数据存储到变量中?

  •  -1
  • RoyBarOn  · 技术社区  · 6 年前

    我正在使用react,我需要将一些API请求存储到变量中,以便进行一些修改。

    我想这样做:

    function getMovies() {
    
    var moviesArr = '';
    return fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=4344343' +
    'd61a2e5')
    .then((response) => response.json())
    .then((json) => moviesArr = json);
    
      }
    
     const currentMoviesArray = getMovies() // Then to recieve the movies data
    

    所以const current moviesarray最终会把提取的数据带回来

    2 回复  |  直到 6 年前
        1
  •  0
  •   user8599269    6 年前

    而不是将其存储到变量中。您可以将响应设置为一个状态变量,这样就可以在组件的每个位置使用它。

    function getMovies() {
      return fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=4344343' +
      'd61a2e5')
     .then((response) => response.json())
     .then((json) => this.setState({moviesArr:json});
    }
    
        2
  •  -1
  •   Sergio Alen    6 年前

    函数 getMovies() 返回承诺。因此,您可以设置 currentMoviesArray 从内部 then() 处理程序,或者使用async/await重构函数,async/await等待满足并返回结果的承诺,请参见下面的两个选项:

    选项1:

    const currentMoviesArray = [];
    
    function getMovies() {
      fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=4344343' +
      'd61a2e5')
      .then((response) => response.json())
      .then((movies) => currentMoviesArray.push(movies));
    }
    

    选项2:

    async function getMovies() {
      await fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=4344343' + 'd61a2e5')
        .then((response) => response.json());
    }
    
    const currentMoviesArray = getMovies();