我想禁用用户进入登录页面,一旦他们使用导航登录,只有进入登录页面,如果他们没有登录,但我得到这个错误,导航不是一个路由组件。我使用的是react路由器dom v6,所以重定向也不起作用。我试着寻找解决办法,但没有一个对我有效。下面是我的代码:
import React from 'react';
import {BrowserRouter as Router, Route, Routes, Navigate} from 'react-router-dom'
import MasterLayout from './layouts/admin/MasterLayout';
import Home from './components/frontend/Home'
import Dashboard from './components/admin/Dashboard';
import Profile from './components/admin/Profile';
import Login from './components/frontend/auth/Login';
import Register from './components/frontend/auth/Register';
import axios from 'axios';
axios.defaults.baseURL = "http://localhost:8000";
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.post['Accept'] = 'application/json';
axios.defaults.withCredentials = true;
axios.interceptors.request.use(function (config){
const token = localStorage.getItem('auth_token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route exact path="/" element={<Home/>} />
<Route path="/login">
{localStorage.getItem('auth_token') ? <Navigate to='/' /> : <Login />}
</Route>
<Route path="/register">
{localStorage.getItem('auth_token') ? <Navigate to='/' /> : <Register />}
</Route>
<Route path="/admin/*" element={<MasterLayout />}>
<Route path="dashboard" element={<Dashboard />} />
<Route path="profile" element={<Profile />} />
</Route>
</Routes>
</Router>
</div>
);
}
export default App;
很显然,在路由组件内部作为子组件传递的组件是v5的工作方式。如果我们可以在v6中工作,你可以使用元素prop来发送组件。
你需要把你的路由改成这样。
<Route path="/login" element={localStorage.getItem('auth_token') ? <Navigate to="/" /> : <Login />} />
<Route path="/register" element={localStorage.getItem('auth_token') ? <Navigate to='/' /> : <Register />} />