我很想弄清楚为什么私有路由没有重定向到我设置的路径。我想念一些东西,但我不知道。 有人帮我弄清楚吗?
这是我的私人路线组件:
import React, {useContext} from 'react';
import {Route, Redirect} from 'react-router-dom';
import AuthContext from '../../context/auth/Authcontext';
const PrivateRoute = ({component: Component, ...rest}) => {
const authContext = useContext(AuthContext);
const {isAuthenticated, loading} = authContext;
return (
<Route
{...rest}
render={props =>
!isAuthenticated && !loading ? (
<Redirect to='/pagelist' />
) : (
<Component {...props} />
)
}
/>
);
};
export default PrivateRoute;
我正在使用上下文来处理所有身份验证部分。我想做的是,如果您未登录,则无法访问仪表板。
这是我的App.js:
import React, {Fragment, Component} from 'react';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import Navbar from './components/layouts/Navbar';
import Dashboard from './components/pages/Dashboard';
import Register from './components/auth/Register';
import Login from './components/auth/Login';
import PrivateRoute from './components/routing/PrivateRoute';
import AuthState from './context/auth/AuthState';
import AlertState from './context/alert/AlertState';
import setAuthToken from './utils/setAuthToken';
if (localStorage.token) {
setAuthToken(localStorage.token);
}
const App = () => {
return (
<AuthState>
<AlertState>
<Router>
<Fragment>
<Navbar />
<div className='container'>
<Alerts />
<Switch>
<PrivateRoute exact path='/' component={Dashboard} />
<Route exact path='/register' component={Register} />
<Route exact path='/login' component={Login} />
</Switch>
</div>
</Fragment>
</Router>
</AlertState>
</AuthState>
);
};
export default App;
我认为我所做的一切都正确,因为当我在控制台中观看时,当前用户未通过身份验证,但仪表板仍可访问。我错过了什么 ?