【问题标题】:Pass State to Private Nested Routes on React Router v6在 React Router v6 上将状态传递给私有嵌套路由
【发布时间】: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


【解决方案1】:

试试这个来获取 v6 中的状态:

    const location = useLocation()
    console.log(location)
    const state = location.state
    console.log(state)

【讨论】:

    【解决方案2】:

    这发生在我在历史状态中传播对象时。

    <MenuItem
      onClick={() => {
        history("/users/form", {
          state: { isNew: false, ...row },
        })
      }}
    >
      Edit
    </MenuItem>
    

    这解决了问题

    <MenuItem
      onClick={() => {
        history("/users/form", {
          state: {
            isNew: false,
            type: row.type,
            email: row.email,
            kind: row.kind || "",
            role: row.role,
            permissions: row.permissions,
          },
        })
      }}
    >
      Edit
    </MenuItem>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2022-01-17
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多