So I have a small login to an API and my problem now is that if the login didn't worked, I am displaying an alert message. But when I am passing the good user I'm getting that the error object res.errors[0] is undefined (which of course is true). What is a good way to remake this code to work on both?
所以我有一个小的API登录,我现在的问题是,如果登录不起作用,我正在显示一条警告消息。但是当我传递好用户时,我得到的是错误对象res.errors [0]未定义(当然这是真的)。重置此代码以兼顾两者的好方法是什么?
Here is my code:
这是我的代码:
LoginAPI.getToken(this.state.value)
.then((res) => {
if (typeof res.errors[0] !== 'undefined') {
if (res.errors[0].code === 'auth.credentials') {
this.setState({
error: 'Username or Password are incorrect!',
isLoading: false,
token: null
});
Alert.alert(
'Login',
this.state.error
)
}
}
else {
this.setState({ token: res });
LoginAPI.getUser(this.state.token)
.then((res) => {
Actions.dashboard({userData: res});
});
this.setState({
isLoading: false
});
}
}).catch((error) => {
console.error(error);
});
Thank you for your time!
感谢您的时间!
1 个解决方案
#1
2
When checking for a nested value in an object or array you should check it like this.
检查对象或数组中的嵌套值时,应该像这样检查它。
if (res && res.errors && res.errors[0] && res.errors[0].code === 'auth.credentials') {
if(res && res.errors && res.errors [0] && res.errors [0] .code ==='auth.credentials'){
Most likely it's trying to read a property of an undefined object property, and JavaScript does not like that. So your logic would look something more like this.
很可能是它试图读取未定义对象属性的属性,而JavaScript不喜欢这样。所以你的逻辑会看起来更像这样。
LoginAPI.getToken(this.state.value)
.then((res) => {
if (res && res.errors && res.errors[0] && res.errors[0].code === 'auth.credentials') {
this.setState({
error: 'Username or Password are incorrect!',
isLoading: false,
token: null
});
Alert.alert(
'Login',
this.state.error
)
}
else {
this.setState({ token: res });
LoginAPI.getUser(this.state.token)
.then((res) => {
Actions.dashboard({userData: res});
});
this.setState({
isLoading: false
});
}
}).catch((error) => {
console.error(error);
});
#1
2
When checking for a nested value in an object or array you should check it like this.
检查对象或数组中的嵌套值时,应该像这样检查它。
if (res && res.errors && res.errors[0] && res.errors[0].code === 'auth.credentials') {
if(res && res.errors && res.errors [0] && res.errors [0] .code ==='auth.credentials'){
Most likely it's trying to read a property of an undefined object property, and JavaScript does not like that. So your logic would look something more like this.
很可能是它试图读取未定义对象属性的属性,而JavaScript不喜欢这样。所以你的逻辑会看起来更像这样。
LoginAPI.getToken(this.state.value)
.then((res) => {
if (res && res.errors && res.errors[0] && res.errors[0].code === 'auth.credentials') {
this.setState({
error: 'Username or Password are incorrect!',
isLoading: false,
token: null
});
Alert.alert(
'Login',
this.state.error
)
}
else {
this.setState({ token: res });
LoginAPI.getUser(this.state.token)
.then((res) => {
Actions.dashboard({userData: res});
});
this.setState({
isLoading: false
});
}
}).catch((error) => {
console.error(error);
});