同步链接: https://www.shanejix.com/posts/[Snippet] - react router authentication/
file tree
.
├── conponents
└── Authentication.tsx
├── pages
├── Home.tsx
├── Login.tsx
└── Management.tsx
├── routes
├── privateRoutes.tsx
└── publicRoutes.tsx
├── App.tsx
App.tsx
import React, { useState } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import publicRoutes from "./routes/publicRoutes";
import privateRoutes from "./routes/privateRoutes";
import Authentication from "./components/Authentication";
function App() {
const [user, setUser] = useState({});
const loginAsUser = () => {
setUser({
role: ["user"],
});
};
return (
<Router>
<Switch>
{publicRoutes.map(({ path, component: Component, ...route }) => (
<Route
key={path}
path={path}
render={(routeProps: any) => (
<Component loginAsUser={loginAsUser} {...routeProps} />
)}
{...route}
/>
))}
{privateRoutes.map((route) => (
<Authentication key={route.path} {...route} user={user} />
))}
</Switch>
</Router>
);
}
export default App;
publicRoutes.ts
import Login from "../pages/Login";
import Home from "../pages/Home";
const publicRoutes = [
{
path: "/login",
component: Login,
exact: true,
},
{
path: "/",
component: Home,
exact: true,
},
];
export default publicRoutes;
privateRoutes.ts
import Management from "../pages/Management";
const privateRoutes = [
{
path: "/management",
component: Management,
exact: true,
role: "user",
backUrl: "/login",
},
];
export default privateRoutes;
Authentication.tsx
import React from "react";
import { Route, Redirect } from "react-router-dom";
function Authentication(props: any) {
const {
user: { role: userRole },
role: routeRole,
backUrl,
...otherProps
} = props;
// 如果用户有权限,就渲染对应的路由
if (userRole && userRole.includes(routeRole)) {
return <Route {...otherProps} />;
} else {
// 如果没有权限,返回配置的默认路由
return <Redirect to={backUrl} />;
}
}
export default Authentication;
注意:react-router-dom 所依赖的版本为 "^5.3.3"
作者:shanejix
出处:https://www.shanejix.com/posts/[Snippet] - react router authentication/
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
声明:转载请注明出处!