在用户登录时使用protected.route
我们如何让用户导航到像Dashboard
和这样的私人路线ViewDetails
?如果他是管理员用户,则显示 Dashboard,否则显示 ViewDetails 屏幕。有人可以就此提出建议。我添加了一个codesandbox链接以供参考
Codesandbox链接
https://codesandbox.io/s/tender-cerf-kss82?file=/src/components/Login.js
login.js
import { useState } from "react";
import { useHistory } from "react-router-dom";
const loginData = [
{ id: 1, email: "mat@test.com", password: "admin123", access: "admin" },
{ id: 1, email: "duo@test.com", password: "test123", access: "user" }
];
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const history = useHistory();
const onSubmit = (email, password) => {
if (
email === loginData[0].email &&
password === loginData[0].password &&
loginData[0].access === "admin"
) {
history.push("/");
} else {
history.push("/ViewDetails");
}
};
return (
<div>
Login Page <br></br>
<input
type="text"
name="email"
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="text"
name="password"
onChange={(e) => setPassword(e.target.value)}
/>
<input type="button" value="submit" onClick={onSubmit(email, password)} />
</div>
);
};
export default Login;
protected.route.js
import React from "react";
import { Route, Redirect } from "react-router-dom";
export const ProtectedRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={(props) => {
if (localStorage.getItem("loginEmail")) {
return <Component {...props} />;
} else {
return (
<>
<Redirect
to={{
pathname: "/login",
state: {
from: props.location
}
}}
/>
</>
);
}
}}
/>
);
};
App.js
import React, { useState } from "react";
import "./styles.css";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Dashboard from "./components/Dashboard.js";
import Login from "./components/Login.js";
import ViewDetails from "./components/ViewDetails.js";
import UserLoginProvider from "./components/UserLoginProvider.js";
import UserProfileProvider from "./components/UserProfileProvider.js";
import ProtectedRoute from "./components/protected.route.js";
import ReactDOM from "react-dom";
//var ReactDOM = require("react-dom");
const App = () => {
return (
<BrowserRouter>
<UserLoginProvider>
<UserProfileProvider>
<>
<Switch>
<ProtectedRoute exact path="/" component={Dashboard} />
<ProtectedRoute path="/ViewDetails" component={ViewDetails} />
<Route path="/Login" component={Login} />
</Switch>
</>
</UserProfileProvider>
</UserLoginProvider>
</BrowserRouter>
);
};
ReactDOM.render(
React.createElement(App, null),
document.getElementById("root")
);
export default App;