javascript - react-native fetch().then() 返回对象对象

标签 javascript react-native promise fetch return-value

我做的网络请求和react-native的示例代码很相似。

网络.js

export default class Networking {

  static tryLogin() {

    return fetch('https://exampleserver.com')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson;
    })
    .catch((error) => {
      console.error(error);
    });

  }
}

我想检索 responseJson 并在另一个类中处理它,但是,.then((responseJson) 返回的是 objectObject 而不是我的 JSON。我正在使用 Networking 调用此方法.tryLogin();

当用 alert(responseJson) 替换 return responseJson 时,它按预期工作,所以它必须与返回有关。

编辑: 在执行 console.log() 时,我得到:

 Promise {
   "_40": 0,
   "_55": null,
   "_65": 0,
   "_72": null,
}

最佳答案

您正在 tryLogin() 中返回一个 Promise。所以你需要在 .then() 方法中访问它的值:

Networking.tryLogin().then(response => console.log(response));

除了评论中提出的问题外,如 react-native docs 中所述:

Networking is an inherently asynchronous operation. Fetch methods will return a Promise that makes it straightforward to write code that works in an asynchronous manner.

关于javascript - react-native fetch().then() 返回对象对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54606340/

相关文章:

javascript - 如何在向下和向上滚动时触发 css 动画

javascript - 禁用防止 ancor 'a' 标签的默认值

javascript - autoRehydrate 在 redux-persist 中有什么用,为什么它在 v5 上被删除了?

javascript - 如何在 Axios promise 响应中的 $scope 中赋值?

javascript - Promise 函数需要使用 return 吗?

javascript - 正则表达式密码验证 - Codewars

javascript - 无法读取未定义错误的属性 'push'?

javascript - 将按钮添加到我的 React Native 应用程序时出现错误?

android - 来自 JS 的错误调用 : field sizes are different [[8, 39],[4,0]

javascript - 在 1 个 http 请求中解决多个 Promise