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

时间:2019-02-24 17:13:34

标签: reactjs fetch

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

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不是一个函数

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

谢谢

2 个答案:

答案 0 :(得分:2)

首先流派不是数组,而是一个函数,因此不会在其上定义过滤器

第二,类型目前不返回任何内容

第三,体裁是一种异步方法,因此您需要处理Promise。您可以使用异步等待功能

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);
  }
}

答案 1 :(得分: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));
}
相关问题