簡體   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