【问题标题】:react Invalid attempt to spread non-iterable instance反应无效尝试传播不可迭代的实例
【发布时间】:2019-07-18 05:08:45
【问题描述】:

我不断收到此错误: TypeError:传播不可迭代实例的无效尝试 当我试图在这里获取一些数据时:

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

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

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

并在此处更新我的组件的状态:

componentDidMount() {
    const genres = [{ _id: "", name: "All Genres" }, ...getGenres()];
    this.setState({ genres});

  }

我知道问题来自这样一个事实,即流派返回一个对象,而状态应该是一个数组,但我不知道如何解决它。

谢谢

【问题讨论】:

    标签: reactjs fetch setstate


    【解决方案1】:

    getGenres 返回一个承诺,因此您需要等待它解决,然后再尝试将其返回的内容置于状态。

    componentDidMount() {
      getGenres().then(res => {
        const genres = [{ _id: "", name: "All Genres" }, ...res];
        this.setState({ genres });
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2021-01-28
      • 2019-07-01
      • 1970-01-01
      • 2021-01-14
      相关资源
      最近更新 更多