2017-03-06 82 views
0

LOGIN按鈕,其中有onPress = this.props.onPressLogin(this.state.email, this.state.password)組件。如何在React native中以登錄失敗顯示警報給用戶

onPressLogin直接調用動作發生器,loginAct

const mapDispatchToProps = (dispatch) => { 
    return { 
     onPressLogin: (email, password) => { 
      dispatch(loginAct(email, password)) 
     } 
    } 
}; 

loginAct實際上是一種,這回異步函數,最後其回調產生作用。

exports.loginAct = (email, password) => { 
    return function (dispatch) { 
     return axios.post('http://10.0.2.2:3000/login', { email: email, password : password }) 
      .then((response) => { 
       if(response.data.result == 'success') { 
        dispatch(authUser(email)); 
       } else { 
        // I want to show alert to user. 
        dispatch(alertUser(response.data.message)); 
       } 
      }) 
      .catch(function (error) { 
       throw error; 
      }) 
    }; 
}; 


alertUser = (alert) => { 
    return { 
     type: 'ALERT_USER', 
     alert 
    } 
}; 

此時我不知道如何正確提醒用戶。這是正確的方式嗎?我這樣做,如果ALERT_USER行動產生了減速處理這個

case 'ALERT_USER' : 
     return { 
      sysAlert : action.alert 
     }; 

而在組件,

if(this.props.sysAlert != ''){ 
     Alert.alert(
      'Alert title', 
      this.props.sysAlert) 
    } 

這樣看起來工作,但我不知道正確的方式。警報之後,this.props.sysAlert不爲空,所以每次組件移動顯示的空警報時。我不知道如何將默認設置爲this.props.sysAlert

我應該創建CLEAR_ALERT操作嗎?所以當警報窗口消失,然後在REDX存儲清潔sysAlert?我認爲這很複雜,有什麼更好的主意?

回答

1

我看到您正在使用來自React-Native的Alert。因此,你可以簡單地做:

alertUser = (alert) => { 
    Alert.alert('Alert title', alert); 
    return { 
     type: 'ALERT_USER', 
     alert 
    } }; 

或者,如果你想顯示旁邊輸入的錯誤信息,你可以使用如下語法:

<Inputs /> 
{this.props.error && <ErrorMsg />} 

由於您使用的終極版連接它會自動更新this.props.error。在這種情況下,你需要將狀態映射到道具上。