【发布时间】:2020-07-07 17:50:27
【问题描述】:
我无法在我的 React Native 项目中返回 API 调用的响应。
let response = fetch('http://3.133.123.120:8000/auth/token', {
method: "POST",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
client_id: 'NTMtzF7gzZPU9Ka35UFsDHvpR8e4D1Fy4OPRsurx',
grant_type: 'password',
username: user,
password: pass,
})
})
.then((response) => response.json())
.then((response) => this.setState({jsonData: response}))
.then(() => alert('resposne jsonData: ' + JSON.stringify(this.state)));
alert('resposne jsonData: ' + JSON.stringify(response))
上面的代码在底部的 .then() 语句中返回了正确的响应,但是,我无法在 fetch() 语句之外使用数据。
我尝试在 fetch() 之外使用的任何东西(比如我在底线的警报)都给了我以下...
{"_40":0,"_65":0,_55":null,"_72":null}
另请注意,这一切都在 React 类组件中
【问题讨论】:
-
如果你想在fetch函数外使用response,你应该将response设置为async函数,或者使用Promise。
标签: javascript request fetch