war*_*ape 0 javascript react-native firebase-authentication react-redux
我正在使用 React Native/Firebase/Redux 构建一个简单的登录系统。我正在尝试找出如何捕获由于登录尝试失败而发生的错误。
这是我的 authscreen.js:
const [alertShowing, setAlertShowing] = useState(false);
const [alertMessage, setAlertMessage] = useState('');
...
function handleLogin() {
const response = dispatch(login(email, password));
console.log(response);
}
Run Code Online (Sandbox Code Playgroud)
动作.js:
export const login = (email, password) => {
return async (dispatch) => {
try {
const response = await Firebase.auth().signInWithEmailAndPassword(email, password);
dispatch(getUser(response.user.uid));
} catch (e) {
return e;
}
};
};
Run Code Online (Sandbox Code Playgroud)
上面的 console.log(response) 正确地向我显示了错误消息,但这显然对用户来说不是很有用。另请注意,使用正确的凭据我可以正确登录。
我真正想做的handleLogin()
是检查响应是否是错误,如果是,setlAlertShowing(true)
以及setAlertMessage
我从 useDispatch 挂钩返回的内容,以便我可以很好地向用户显示它。
我该怎么办?TIA。
Firebase 错误消息是为开发人员设计的,对标准用户不友好。解决方案是识别身份验证错误代码并映射到用户友好的消息。
错误代码列表https://firebase.google.com/docs/auth/admin/errors
您可以使用这样的函数将 authError 映射到有意义的错误消息。
function mapAuthCodeToMessage(authCode) {
switch (authCode) {
case "auth/invalid-password":
return "Password provided is not corrected";
case "auth/invalid-email":
return "Email provided is invalid";
// Many more authCode mapping here...
default:
return "";
}
}
Run Code Online (Sandbox Code Playgroud)
并稍后使用它
export const login = (email, password) => {
return async (dispatch) => {
try {
const response = await Firebase.auth().signInWithEmailAndPassword(email, password);
dispatch(getUser(response.user.uid));
} catch (e) {
dispatch({type:"authError",message:mapAuthCodeToMessage(e.code)}));
}
};
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3013 次 |
最近记录: |