我希望每次导航到路线时都会调用一个通用组件。此组件的主要用途是身份验证。为了更好地说明我的需要,我有这个例子,如果vue.js:
const routes = [
{ path: '/', component: Login, meta: { auth: false } },
{ path: '/dashboard', component: Dashboard, meta: { auth: true } },
];
router.beforeEach((to, from, next) => {
if( to.meta.auth ) {
// run auth, then next();
} else {
next();
}
})
我可以在ReactJs中实现这样的smth吗?
答案 0 :(得分:1)
您可以创建包含登录逻辑的react组件。此组件包装需要经过身份验证的用户的所有路由。请查看此article以获取解决方案。
答案 1 :(得分:1)
在react-router
的文档中(假设您将使用此路由器库),有一个如何实现经过身份验证的路由的示例:https://reacttraining.com/react-router/web/example/auth-workflow
使用您的示例,您可以像这样实现它
import React, { Component } from 'react';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
import Login from './Login';
import Dashboard from './Dashboard';
const routes = [
{ path: '/', component: (props) => <Login {...props} />, meta: { auth: false } },
{ path: '/dashboard', component: (props) => <Dashboard {...props} />, meta: { auth: true } },
];
export default class MyRouter extends Component {
isLoggedin() {
// run auth check that will return true/false
return true;
}
render() {
// if loggedin => render component, if not => redirect to the login page
const PrivateRoute = ({ component: RouteComponent, ...rest }) => (
<Route
{...rest}
render={props => (
this.isLoggedin() ? (
<RouteComponent {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
)}
/>
);
return (
<BrowserRouter>
<Switch>
{routes.map((route, index) => (
route.meta.auth ?
<PrivateRoute key={index} path={route.path} exact component={route.component} />
:
<Route key={index} path={route.path} exact component={route.component} />
))}
</Switch>
</BrowserRouter>
);
}
}
在PrivateRoute中,我们将使用this.isLoggedIn()
检查身份验证状态,并根据返回的布尔值,呈现组件或重定向(例如登录页面)。