我正在开发一个应用程序(非常简单的应用程序(,它请求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、代码、注释等(期望所有 url 都是空字符串。
this.setState
前console.log(samples)
的结果:
{
"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": [
""
]
}
找不到原因。
有什么想法吗?非常感谢。
samples
是一个JavaScript纯对象。如果预期结果是在传递给.setState()
的对象的属性"data"
定义Array
,则设置samples.pictures
并在"data"
属性处.concat()
samples.thumbs
。
从链接到fetch()
呼叫.then()
中删除throw
以避免意外结果。
data: samples.pictures.concat(samples.thumbs)
> 谢谢@YaSH,你是对的。使用 HTTPS 网址,字符串不为空...但是为什么。。。我在文档中没有找到任何提及这一点的内容......
@guest271314:这等于调用 fetch 的组件。