【发布时间】:2015-07-15 16:44:55
【问题描述】:
我正在使用 react native 为 iPhone 编写小应用程序。我正在尝试使用 fetch 从网站获取 JSON 数据。就像在示例中一样:
function status(response) {
if (response.status >= 200 && response.status < 300) {
return response
}
throw new Error(response.statusText)
}
function json(response) {
return response.json()
}
fetch('/users', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
}).then(status)
.then(json)
.then(function(json) {
console.log('request succeeded with json response', json)
}).catch(function(error) {
console.log('request failed', error)
})
一切正常,但我需要稍后使用该数据。当我尝试将它分配给 json 函数中的某个变量时,我得到“请求错误”,然后(正确地)获取数据。获取该数据并将其保存在某个变量中以供以后使用的最佳做法是什么?
【问题讨论】:
标签: javascript ios json react-native fetch-api