【发布时间】:2021-06-05 07:01:34
【问题描述】:
这是我的 App.js:
function App() {
return (
<BrowserRouter>
<AuthProvider>
<Switch>
<PrivateRoute path="/" component={MainPage} />
<PrivateRoute path="/admin" component={MainPage} />
<Container
className="d-flex align-items-center justify-content-center"
style={{ minHeight: "100vh" }}
>
<div className="w-100" style={{ maxWidth: "400px" }}>
<Route path="/signup" component={Signup} />
<Route path="/login" component={Login} /> //The component part
<Route path="/forgot-password" component={ForgotPassword} />
</div>
</Container>
</Switch>
</AuthProvider>
</BrowserRouter>
);
}
来自 firebase 的 PriveRoute 组件的身份验证上下文:
export default function PrivateRoute({ component: Component, ...rest }) {
const { currentUser } = useAuth();
return (
<Route
render={(props) => {
return currentUser ? <Admin {...props} /> : <Redirect to="/login" />; // it redirects when the user does not log in.
}}
></Route>
);
登录组件:
export default function Login() {
const emailRef = useRef();
const passwordRef = useRef();
const { login, currentUser } = useAuth();
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const history = useHistory();
if (currentUser) {
history.push("/admin/mainpage");
}
async function handleSubmit(e) {
e.preventDefault();
try {
setError("");
setLoading(true);
await login(
emailRef.current.value + "@myosmail.com",
passwordRef.current.value
);
history.push("/admin/mainpage");
} catch {
setError("Failed to log in");
}
setLoading(false);
}
return (
<>
<Card>
<Card.Body>
<h2 className="text-center mb-4">Log In</h2>
{error && <Alert variant="danger">{error}</Alert>}
<Form onSubmit={handleSubmit}>
<Form.Group id="email">
<Form.Label>Username</Form.Label>
<Form.Control ref={emailRef} required />
</Form.Group>
<Form.Group id="password">
<Form.Label>Password</Form.Label>
<Form.Control type="password" ref={passwordRef} required />
</Form.Group>
<Button disabled={loading} className="w-100" type="submit">
Log In
</Button>
</Form>
<div className="w-100 text-center mt-3">
<Link to="/forgot-password">Forgot Password?</Link>
</div>
</Card.Body>
</Card>
<div className="w-100 text-center mt-2">
Need an account? <Link to="/signup">Sign Up</Link>
</div>
</>
);
}
如果用户没有登录,我想构建一个组件,它无法访问我网站的内容,所以我构建了上面的组件。但问题是,当我打开我的页面并且没有登录时,页面将我重定向到“/login”,但没有呈现登录组件,我不明白问题出在哪里。我调试了我的组件,我看到我的代码首先转到 PrivateRoute 组件,然后它重定向到“/ login”,但是当页面重定向到 Login 时没有呈现任何内容。当我从 App.js 中删除 PrivateRoutes 时,我的代码工作正常。
【问题讨论】:
标签: javascript reactjs react-router react-router-dom