我正在使用反應本機編寫iPhone的小應用程序。我正嘗試使用fetch從網站獲取JSON數據。像這樣的例子:如何從提取獲取JSON數據(react-native)
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函數中的某個變量時,我收到「請求錯誤」,然後獲取數據(正確)。獲取這些數據的最佳做法是什麼,並在稍後將其用於某些變量中?
,則通常有兩個thens這樣的:'。然後((響應)=> { response.text(); 的console.log(響應); }) 。然後((responseText的)=> { 的console.log(responseText的); }) .catch((誤差)=> { console.warn(誤差); }) .done();'我想知道什麼那麼兩人中的每一個人都會回來嗎?爲什麼這樣組織?他們如何工作? –
@KevinZhao:2然後順序執行,第1個是從響應對象中獲取文本,第二個是打印文本值。 – vignesh