我做的网络请求和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/