繁体   English   中英

如何在React Native中无效的登录凭据时显示警告消息?

[英]How to show alert message when invalid login credentials in React Native?

我希望在用户登录失败时显示警告消息。但是没有显示警报。以下是我的代码本身的反应。

登录

   onPressLogin(){
    fetch('http://192.168.1.10:3000/users/login',{
        method: 'POST',
        headers:{
                'Content-Type' : 'application/json',
        'Accept':'application/json'
            },
            body: JSON.stringify({
                contact:this.state.contact,
                password: this.state.password,
            })
})
  .then(response => response.json())
  .then((responseData) =>
        {
    this.setState({
        userdetail: responseData,
        })
if(responseData){
  setTimeout(() => {
    Actions.firstScreen();
  }, 2300);
  AsyncStorage.saveItem('userid', this.state.userData.phone_no);

} else {
  console.log(responseData);
  Alert(responseData);
}
}); 

}

我现在得到的是它会在成功登录时重定向到firstScreen ,但它不会在登录失败时发出警告。当我安慰我得到意外结束的json输入错误但是我使用节点js作为后端错误结果以下是我在nodejs中的代码

else {
                 appData.error= 1;
                 appData["data"] = "Phone number and Password does not match";
                 res.status(204).json(appData);
                 console.log(appData);
               }
             }else{
               appData.error=1;
               appData["data"] ="Phone number does not exist";
               res.status(204).json(appData);
               console.log(appData);
             }

appData的安慰结果是

{ error: 1, data: 'Phone number does not exist' }

我不知道为什么这个错误消息没有显示在responseData in react native中。

onPressLogin(){
fetch('http://192.168.1.10:3000/users/login',{
    method: 'POST',
    headers:{
            'Content-Type' : 'application/json',
    'Accept':'application/json'
        },
        body: JSON.stringify({
            contact:this.state.contact,
            password: this.state.password,
        })
})
.then(response => response.json())
.then((responseData) =>{
    if(responseData.error !== 1){ // verify the success case, as you didn't provide the success case i am using the error code 
        this.setState({ // its recommended you verify the json before setting it to state.
            userdetail: responseData,
        })
        setTimeout(() => {
            Actions.firstScreen();
        }, 2300);
        AsyncStorage.setItem('userid', this.state.userData.phone_no); // its setItem not saveitem.
    } else {
        console.log(responseData);
        Alert.alert(JSON.stringify(responseData)); // Alerts doesn't allow arrays or JSONs, so stringify them to view in Alerts
    }
}).catch((error) => {
    // handle catch
    console.log("error:"+JSON.stringify(error));
});

}

始终在承诺结束时使用'catch'并处理它们。

如果您仍然面临这个问题,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM