无法处理从服务器获取的数据

问题描述 投票:0回答:2

我正在尝试使用以下代码获取数据:

export const genres =()=>{
const apiUrl = "http://localhost:3000/api";
fetch(apiUrl + "/genres")
  .then(response => response.json())
  .then(data => {
    const res = data.results
    return res
  }) 
} 

那么我想用这段代码来结果

export function getGenres() {
  return genres.filter(g => g);
}

但我明白了:TypeError:genres.filter不是一个函数。

我的错误是什么以及如何解决?

谢谢

reactjs fetch
2个回答
2
投票

首先,类型不是数组,而是函数,因此不会在其上定义过滤器

其次,流派目前没有返回任何东西

第三,类型是一种异步方法,所以你需要处理promises.You可以使用异步等待它

export const genres =()=>{
    const apiUrl = "http://localhost:3000/api";

    return fetch(apiUrl + "/genres")
      .then(response => response.json())
      .then(data => {
        const res = data.results
        return res
      }) 

}

export async function getGenres() {
  try {
     const res = await genres();
     return res.filter(g => g);
  } catch(e) {
     console.log('err', e);
  }
}

0
投票

genres是一个函数,所以你不能直接使用filter

您可以调用genres函数并返回fetch承诺并等待它解决,然后才能对res做任何事情。

export const genres = () => {
  const apiUrl = "http://localhost:3000/api";

  return fetch(apiUrl + "/genres")
    .then(response => response.json())
    .then(data => {
      const res = data.results;
      return res;
    });
};

export function getGenres() {
  return genres().then(res => res.filter(g => g));
}
© www.soinside.com 2019 - 2024. All rights reserved.