[英]I could display API data in my console.log, but I can't setState with it . . . how can I setState? (fetch, React Native)
[英]How can I log in to an API and catch login errors using fetch on React Native?
我正在制作一个需要登录API的应用程序。 我有一个登录表单,该表单将ID号和密码发送给API,并且API应该这样响应:
[
{
"user_id":"032984",
"user_number":"140521351",
"token":"990nZtMtEUUMY"
}
]
如果出现登录错误,API将响应:
[
{
"ERROR": "INVALID PASSWORD | NOT FOUND 1SELECT user_id, lastname, password, user_number FROM user where user_number = 'INVALIDVALUE'",
},
]
我希望能够使用if语句捕获登录错误,例如在此JSON中是否存在ERROR对象,显示警报,否则登录并将user_id和token保存到可以在应用程序的不同屏幕中使用的变量中向API发送更多请求,以JSON获取这些响应,并显示我需要的数据。
我怎样才能做到这一点?
到目前为止,这是我的登录功能的代码:
// login function
_userLogin = () => {
this.setState({ isLoggingIn: true, message: '' });
// send request to API properly
fetch("https://api.company.com/v4/users/json.php", {
method: "POST",
// our headers
headers: {
'Content-Type': 'application/json',
'Connection': 'close',
'Accept': '*/*',
'User-Agent': 'InternalApp/0.1 (InternalApp; ReactNative) Expo/33',
'Accept-Language': 'en-US;q=1.0',
'Accept-Encoding': 'gzip, deflate'
},
// body of the request with number/password
body: JSON.stringify({
user_number: this.state.number,
password: this.state.password,
}),
})
.then(response => {
return response.json(); // make it json?!
}).then(responseData => {
// debug messages
console.log(responseData);
console.log("Moving on to parsing JSON"); // CODE WORKS TO HERE
// parse json
var jsonObj = JSON.parse(responseData); // CODE STUCK HERE
// debug messages
console.log("JSON parsed");
if (jsonObj.ERROR)
console.log("Error caught");
else
this.setState(prevState => ({
credentialJson: prevState.credentialJson = responseData,
isLoggingIn: false,
}))
this.props.onLoginPress();
})
};
我真的是React Native和StackOverflow的新手,请原谅任何格式问题。 我希望我提供了足够的细节。
您的提取库fetch
返回一个Promise
因此,如果API实际上引发错误,则可以添加catch语句。
fetch(url).then().catch((error) => {
console.log("Error", error);
});
另一件事是您的代码停止在JSON.parse的原因是您已经在上一个.then
子句( response.json()
)中解析了json,因此您尝试解析的对象不是字符串,而JSON.parse
期望。
根据您对此答案的评论以及console.log(responseData)
的输出,您的responseData是一个数组,而您的数据是第一个数组元素内的Object。 通过responseData[0]
访问您的数据。 例如:
responseData[0].token
//Should return "990nZtMtEUUMY"
这是检查错误集的方法:
if(responseData[0].ERROR){}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.