我正在使用 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 函数中的某个变量时,出现“请求错误”,然后(正确)获取数据。获取该数据并将其保存在某个变量中以供日后使用的最佳做法是什么?
最佳答案
我是这样做的。我在控制台上显示了响应。您可以根据需要将响应数据存储在状态变量或本地存储中。
doSignUp() {
console.log("inside post api");
fetch('your API URL', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
password: this.state.password,
email:this.state.email,
name: this.state.firstname,
last_name :this.state.last_name,
mobile:this.state.mobile,
ssn:"2222222"
})
}).then((response) => response.json())
.then((responseData) => {
console.log("inside responsejson");
console.log('response object:',responseData)
}).done();
}
关于javascript - 如何从 fetch 中获取 JSON 数据(react-native),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30061625/