【问题标题】:trying to use fetch in componentDidMount shows undefined [react native]尝试在 componentDidMount 中使用 fetch 显示未定义 [react native]
【发布时间】:2020-08-30 22:34:36
【问题描述】:

这是我的 componentDidMount:

componentDidMount(){
    return fetch(API_URL + "/users?email=test@test.com").then(
      (response) => response.json()
    ).then( (responseJson) => {
      console.log("response is " + responseJson.category)
    }).catch((error) => console.log(error))
}

但是,您在那里看到的 console.log 打印:

 response is undefined

当我通过我得到的完全相同的 URL 访问我的 API 时:

[{"category":"Donante","_id":"123","address":"street 32","email":"test@test.com", "__v":0}]

那么为什么我无法在我的代码中获取数据?

【问题讨论】:

  • 您的响应是一个数组 - 至少在这种情况下只包含一个对象。所以看起来你想要responseJson[0].category
  • 天哪,太简单了,谢谢它成功了!!

标签: javascript react-native fetch


【解决方案1】:

由于您将返回一个数组作为响应,因此请确保您首先访问该数组的单个元素!

即,将您的 console.log 更改为 "response is" + responseJson[0].category

【讨论】:

    【解决方案2】:

    这可能是因为fetch 函数返回的承诺在您尝试访问响应对象时尚未实现。

    因此,您可能希望使用以下代码重构代码:

    componentDidMount(){
      const promise = fetch(API_URL + "/users?email=test@test.com").then(res => res.json());
    
      Promise.allSettled([promise]).then(([responseJson]) => {
        // you can access your responseJson here
        console.log(`response is ${responseJson.category}`);
      }
    }
    

    Promise.allSettled 函数返回一个 Promise,它只会在 param 给出的 Promise 被实现或被拒绝时才解析。这样,您就可以访问您可以查看更多详细信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 2016-02-18
      • 1970-01-01
      • 2017-02-04
      • 2019-05-08
      • 2018-01-29
      相关资源
      最近更新 更多