【发布时间】:2021-11-26 05:10:06
【问题描述】:
所以,我已经使用带有嵌套路由的 React Router v6 设置了我的 React 应用路由。
问题是,当我访问我的任何私有路由(定义如下)时,我会丢失会话状态,丢失诸如查询参数和引荐来源网址(以前的路径)之类的信息,我似乎无法弄清楚route 如何将此状态传递给我的 Private 路由组件到子路由。
这是我的路由配置:
App.js:
import routes from './routes';
const App = () => {
const routing = useRoutes(routes);
return (
<ThemeProvider theme={theme}>
<UserProvider>
<GlobalStyles />
{routing}
</UserProvider>
</ThemeProvider>
);
};
export default App;
Index.js:
import App from './App';
ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>
), document.getElementById('root'));
Routes.js:
console.log(location) 显示 location.state 为空
const Private = ({ component: Component, ...rest }) => {
const [state] = React.useContext(UserContext);
const location = useLocation()
const path = location.pathname
console.log(location)
if (state.auth){
console.log('Authenticated');
return <Component {...rest} />
}
else {
console.log('Not Authenticated')
return <Navigate to = {'/login?from=' + path} />
}
};
const routes = [
{
path: 'app',
element: <Private component={DashboardLayout} />,
children: [
{
path: 'account', children: [
{ path: 'integrations', element: <Integrations /> },
]
},
{ path: 'dashboard', element: <Dashboard /> },
{ path: 'audiences', element: <Audiences /> },
{ path: 'creatives', element: <Creatives /> },
{ path: 'copywriting', element: <Copywriting /> },
{ path: 'settings', element: <ProjectSettings /> },
{ path: 'user_settings', element: <UserSettings /> },
{ path: 'fb_interests', element: <FbInterestsExplorer /> },
{ path: '*', element: <NotFound /> },
]
},
{
path: '/',
element: <MainLayout />,
children: [
{ path: 'login', element: <Login /> },
{ path: 'user/activate/:user_id', element: <UserConfirmation /> },
{ path: '/', element: <Navigate to="/app/dashboard" /> },
{ path: '*', element: <NotFound /> }
]
}
];
export default routes;
DashboardLayout.js
const DashboardLayout = () => {
const [isMobileNavOpen, setMobileNavOpen] = useState(false);
return (
<DashboardLayoutRoot>
<DashboardNavbar onMobileNavOpen={() => setMobileNavOpen(true)} />
<DashboardSidebar
onMobileClose={() => setMobileNavOpen(false)}
openMobile={isMobileNavOpen}
/>
<DashboardLayoutWrapper>
<DashboardLayoutContainer>
<DashboardLayoutContent>
<Outlet />
</DashboardLayoutContent>
</DashboardLayoutContainer>
</DashboardLayoutWrapper>
</DashboardLayoutRoot>
);
};
export default DashboardLayout;
【问题讨论】:
-
我遇到了完全相同的问题
标签: reactjs react-router react-router-dom react-router-v6