handleEmailSubmit
函数抛出错误,loginWithEmail
函数也不会捕获任何错误。
可能是我对异步函数缺乏了解。
我需要你的帮助。谢谢。
登录.tsx
const Login: React.FC = () => {
const [errorMsg, setErrorMsg] = useState<string>('');
const history = useHistory();
const handleEmailSubmit = useCallback(async (e) => {
e.preventDefault();
const { email, password } = e.target.elements;
loginWithEmail(email.value, password.value)
.then(() => {
history.push('/');
})
.catch((error) => {
// this block isn't called!
setErrorMsg(error.message);
});
}, []);
return (
<>
<h2>Login</h2>
<form onSubmit={handleEmailSubmit}>
<InputGroup>
<label htmlFor="email">Email</label>
<TextField
id="email"
name="email"
type="email"
/>
</InputGroup>
<InputGroup>
<label htmlFor="password">Password</label>
<TextField
id="password"
name="password"
type="password"
/>
</InputGroup>
<Button type="submit">
送信する
</Button>
</form>
</>
);
}
loginWithEmail
定义
import axios from 'axios';
// firebase
import 'firebase/auth';
import firebase from 'firebase/app';
export const loginWithEmail = async (
email: string,
password: string
): Promise<void> => {
app
.auth()
.signInWithEmailAndPassword(email, password)
.then((userCredential) => {
userCredential.user?.getIdToken(true).then((token: string) => {
axios
.get('https://dev.myserver.com/api/v1/users/auth', {
headers: { Authorization: `Bearer ${token}` },
})
.catch((error) => {
app.auth().signOut();
throw error;
});
});
})
.catch((error) => {
console.log(error);
});
};
答案 0 :(得分:-2)
您需要在 catch 语句中抛出错误。
app
.auth()
.signInWithEmailAndPassword(email, password)
.then((userCredential) => {
userCredential.user?.getIdToken(true).then((token: string) => {
axios
.get('https://dev.myserver.com/api/v1/users/auth', {
headers: { Authorization: `Bearer ${token}` },
})
.catch((error) => {
app.auth().signOut();
throw error;
});
});
})
.catch((error) => {
console.log(error);
throw error; // there could be something wrong here
});