【发布时间】:2017-08-10 14:11:10
【问题描述】:
我正在开发一个应用程序(非常简单的应用程序),它请求一个 JSON API。让我生气的一段代码是:
fetch("http://xxx/api/v1/samples", {
method: "GET",
headers: {
'Authorization': 'Bearer ' + userToken
}
}).then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('error');
}).then((samples) => {
console.log(samples);
this.setState({
data: samples,
error: samples.error || null,
loading: false,
refreshing: false
});
}).catch((error) => {
AlertIOS.alert("OOPS", error.message);
});
API 返回:
{
"code": "4345",
"id": 3,
"comment": "Echantillon trouvé dans un étang",
"updated_at": {
"date": "2017-07-04 11:04:34.000000",
"timezone_type": 3,
"timezone": "Europe/Zurich"
},
"project_name": "Récolte de Lézards",
"thumbs": "http://xxx/storage-app-uploads-public-595-e01-893-595e01893c826572100952-8cf6abfd3440f538dfa95b1d581b7487.png",
"pictures": [
"http://xxx/storage-app-uploads-public-595-e01-893-595e01893c826572100952-8cf6abfd3440f538dfa95b1d581b7487.png"
]
}
我的问题 var "samples" 是正确的(包含所有字段;id、code、comment ......)期望所有 url 都是空字符串。
console.log(samples) 在this.setState 之前的结果:
{
"code": "4345",
"id": 3,
"comment": "Echantillon trouvé dans un étang",
"updated_at": {
"date": "2017-07-04 11:04:34.000000",
"timezone_type": 3,
"timezone": "Europe/Zurich"
},
"project_name": "Récolte de Lézards",
"thumbs": "",
"pictures": [
""
]
}
找不到原因。
有什么想法吗?非常感谢。
【问题讨论】:
-
你能详细说明一下吗?完成
fetch之后,您在用this.state.data做什么? -
你为什么在
.then()throw?alert()被调用了吗?预期的结果是什么? -
@MichaelCheng:目前,我对 this.state.data 不做任何事情(因为它不起作用……)。
-
@guest271314:别扔了;如果删除,它是相同的。我希望,在“样本”中,“拇指”和“图片”的值与 API 请求中的值相同……不调用警报。
-
试试
https网址
标签: javascript json react-native