【发布时间】:2021-03-03 17:58:57
【问题描述】:
我正在使用 react、firebase auth 和 context api 构建身份验证。
signin.js
import React, { useEffect, useState } from 'react';
import { Form, Button, Container, Card } from 'react-bootstrap';
import { useAuth } from '../contextApi/contextApi';
import { Link } from 'react-router-dom';
import { useHistory } from 'react-router-dom';
function SignIn() {
let history = useHistory();
const { signIn } = useAuth();
const emailRef = React.useRef(null);
const passwordRef = React.useRef(null);
const [loading, setLoading] = useState(false);
let handleSubmit = async (e) => {
e.preventDefault();
console.log('connected');
try {
setLoading(true);
await signIn(emailRef.current.value, passwordRef.current.value);
console.log('push');
history.push('/dashboard');
} catch {
alert('handleSubmit went wrong!');
}
history.push('/dashboard');
setLoading(false);
};
return (
<div style={{ backgroundColor: '#a9a9a9' }}>
<Container
className="signin d-flex align-items-center justify-content-center"
style={{
minHeight: '100vh',
}}
>
<Card className="shadow">
<Card.Body>
<h2 className="text-center mb-4">Sign In</h2>
<Form onSubmit={handleSubmit}>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control
type="email"
placeholder="Enter email"
ref={emailRef}
required
/>
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="Password"
ref={passwordRef}
required
/>
</Form.Group>
<Button variant="primary" type="submit" disabled={loading}>
Submit
</Button>
</Form>
<div className="w-100 text-center mt-2">
Need an account? <Link to="/signup">Sign up</Link>
</div>
<div className="w-100 text-center mt-2">
Forgot password? <Link to="/forgotpassword">Click here</Link>
</div>
<div className="w-100 text-center mt-2">
Back to <Link to="/">Home page</Link>
</div>
</Card.Body>
</Card>
</Container>
</div>
);
}
export default SignIn;
只要我成功登录,一切都会很好, 但如果我稍后登录失败,即使我输入了正确的密码/电子邮件,登录页面也不会重定向到仪表板页面。
能否指出我的代码的哪一部分是错误的?
contextApi.js
import React, { useContext, useEffect, useState } from 'react';
import { auth } from '../firebase';
import { useHistory } from 'react-router-dom';
const ContextApi = React.createContext();
export function useAuth() {
return useContext(ContextApi);
}
export const ContextApiProvider = ({ children }) => {
let [currentUser, setCurrentUser] = useState();
let [loading, setLoading] = useState(true);
useEffect(() => {
const unsubscribed = auth.onAuthStateChanged((user) => {
if (user) {
setCurrentUser(user);
setLoading(false);
} else {
setCurrentUser(null);
setLoading(false);
console.log(currentUser);
}
});
return unsubscribed;
}, []);
const signIn = (email, password) => {
auth.signInWithEmailAndPassword(email, password).catch(function (error) {
// Handle Errors here.
console.log(error);
let errorCode = error.code;
let errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('sign in failed! Wrong password.');
} else if (!errorMessage) {
alert('you are signed in!');
} else {
alert(`sign in failed! ${errorMessage}`);
}
});
};
const signUp = (email, password) => {
auth.createUserWithEmailAndPassword(email, password).catch((error) => {
let errorCode = error.code;
let errorMessage = error.message;
console.log(errorMessage);
console.log(error);
console.log(errorCode);
if (errorCode === 'auth/weak-password') {
alert(`signup failed! The password is too weak!`);
} else if (!errorMessage) {
alert('signed up successfully');
} else {
alert(`sign up failed! ${errorMessage}`);
}
});
};
const resetPassword = (email) => {
auth.sendPasswordResetEmail(email).catch((error) => {
let errorCode = error.code;
let errorMessage = error.message;
if (errorCode === 'auth/invalid-email') {
alert('email not found');
} else {
alert(errorMessage);
}
});
};
const logout = () => {
return auth.signOut();
};
let value = {
signIn,
currentUser,
signUp,
resetPassword,
logout,
};
return (
<ContextApi.Provider value={value}>
{!loading && children}
{/* {children} */}
</ContextApi.Provider>
);
};
【问题讨论】:
-
signIn似乎没有返回任何值,也不是异步函数,因此不清楚您在handleSubmit处理程序中的await是什么。您的仪表板上有两个history.push,您是说两个都没有工作吗? -
signin 是 contectApi.js 中 useAuth 的一个函数
-
我知道,您将它作为 sn-p 包含在您的问题中,这就是我知道它不是
async函数也没有返回任何东西的原因,所以我很好奇为什么它是awaited 在用户界面中。 -
它确实是一个异步函数!让 handleSubmit = async (e) => { e.preventDefault(); console.log('已连接');试试 { ... } }
-
????????♂️ 我没有说
handleSubmit不是async函数,它显然在函数签名中是正确的。signIn不是async并且是隐式的 void 返回...等待它不会使 that 函数异步。我指出handleSubmit的async/await毫无意义。回到主题,但我的另一个问题。你知道哪个history.push不工作吗?
标签: javascript reactjs firebase firebase-authentication