【问题标题】:Api fetch - Cannot read property 'json' of undefined [closed]Api fetch - 无法读取未定义的属性“json”[关闭]
【发布时间】:2018-09-30 22:21:52
【问题描述】:

我正在使用这个 API 来制作地图,并且我实施了一些验证,以防在获取数据时出错。实施此解决方案时,出现错误:

未处理的拒绝(TypeError):无法读取未定义的属性“json”

componentDidMount() {
    fetch('https://api.citybik.es/v2/networks')
        .then(res => {                        // *** implemented this
            if (!res.ok) {                    // ***
                throw new Error(res.status);  // ***
            }                                 // ***
        })
        .catch(error => {
            console.log(error);
        })
        .then(res => res.json()) // *** error in this line
        .then(response => {
            const networkData = response.networks;
            this.setState({
                bikeData: networkData
            });
        })
    }

谢谢!

【问题讨论】:

  • 你不会从一开始就返回任何东西,它只处理错误情况。
  • 你有什么建议? @jonrsharpe
  • 要么合并它们,要么返回一些东西让第二个处理。

标签: javascript json reactjs api


【解决方案1】:

为了继续 Promise 链接,您应该为下一个 .then 方法返回一个值。因此,您在第一个 .then 方法中缺少此返回值。正如@jonrsharpe 在 cmets 中解释的那样,您可以将它们结合起来。

componentDidMount() {
  fetch("https://api.citybik.es/v2/networks")
    .then(res => {
      if (!res.ok) {
        throw new Error(res.status);
      }
      return res.json();
    })
    .then(response => {
      const networkData = response.networks;
      this.setState({
        bikeData: networkData
      });
    })
    .catch(error => {
      console.log(error);
    });
}

【讨论】:

  • 谢谢@jonrsharpe 和 devserkan!
猜你喜欢
  • 2017-06-21
  • 2020-09-17
  • 2021-04-17
  • 2019-04-09
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-15
相关资源
最近更新 更多