我无法将授权流抽象到单独的路由组件中。
问题在于,一旦我抽象了身份验证逻辑,该路由的组件就会重新安装。重新安装组件会使 componentDidMount 和 componenentWillUnmount 生命周期方法陷入混乱。
如果我不抽象自定义逻辑,则该组件可以正常工作-无需重新安装。
这是未抽象的代码,但是可以正常工作。
<Route
path={routes.sessionList()}
render={() => isAuthenticated ? <SessionPages.SessionList /> : <NotLoggedInRedirect />}
/>
这是我到目前为止尝试过的:
// route definition
const PrivateRoute = ({ path, component }) => (
<Route
exact
path={path}
render={() => isAuthenticated ? component : <NotLoggedInRedirect />}
/>
);
// router code
<PrivateRoute
path={routes.sessionList()}
component={<SessionPages.SessionList />}
/>
// router code
// method definition
let getPrivateComponent = (Page) => {
let Component = NotLoggedInRedirect;
if(isAuthenticated) Component = () => <ErrorBoundaryContainer><Page /></ErrorBoundaryContainer>;
return Component;
};
// router code
<Route
exact
path={routes.sessionList()}
component={getPrivateComponent(SessionPages.SessionList)}
/>
// router code
在查看反应路由器文档时,他们提到使用render方法将阻止重新安装组件,但是与包装路由组件没有任何关系。 https://reacttraining.com/react-router/web/api/Route/render-func
我会使用工作版本(没有抽象的版本),但是路线很多,而且很混乱,很难维护)
有没有人碰到这种问题?
编辑:我正在使用React Router v5