我正在尝试设置一个 Router
以使用相当于 example 的自定义 PrivateRoute
组件官方 react-router
文档中给出。问题是我还想使用包罗万象的 404 路由,所以我想我也需要使用 Switch
组件,如 this example 所示。来自文档。
这里存在冲突,因为 docs对于 Switch
来说,Switch
组件的子组件必须是 Route
组件,并且在 this issue 中该团队表示,不支持在 Switch
内使用非路由组件,即使它恰好有效。
我已经创建了高阶路由,目前正在 Switch
中使用它们,它似乎正在工作,但这不会通过我公司的代码审查,因为它使用的是不受支持的API 随时可能崩溃。我想知道是否有完全支持的方法来将高阶路由与包罗万象的路由一起使用。
我正在考虑尝试创建 404 路由,而无需使用 Switch
,或者使用常规 Route
组件,但包装传递给 的组件>在身份验证逻辑中路由
。
import { Router, Route, Switch } from 'react-router-dom';
// Array of authorization functions to be tested by private routes
const authCriteria = [
// The next route must have been referred by a previous route
props => defined(props.location.state.from),
];
// Seems to work as expected, but violates the supported use
// of the Switch component
const AppRouter = () => {
return (
<Router>
<Switch>
<Route exact path='/' component={Store} />
<PrivateRoute
exact
path='/account'
component={Account}
authCriteria={authCriteria}
/>
<PrivateRoute
exact
path='/shipping'
component={Shipping}
authCriteria={authCriteria}
/>
<PrivateRoute
exact
path='/checkout'
component={Checkout}
authCriteria={authCriteria}
/>
// Catch-all route means we need to use a Switch
<Route render={() => (<h2>Not Found</h2>)} />
</Switch>
</Router>
);
};
export default AppRouter;
最佳答案
根据您的问题到react-router github的链接,您似乎无法在 Switch
中使用 HOC .
但是,您可以实现类似的目标。基本上,您需要两个路由器。第一个Router
路由所有预先验证的路由,例如登录、新用户、忘记密码等。因为它位于 Switch
内,它应该渲染你的第二个 Router
。你的第二个Router
将包含您的所有身份验证所需的路由。但是,您需要包含条件检查以确保用户经过身份验证。如果用户未经过身份验证,您只需返回 Redirect
返回/login
小路。这是因为第一个 Switch
。如果用户访问未经身份验证的用户无法访问的 URL,则用户将始终被重定向到 /login
因为它们将在第一个开关和Redirect
中达到默认条件。第二个组件。
import { Router, Route, Switch } from 'react-router-dom';
const AppRouter = (props) => {
return (
<Router>
<Switch>
<Route exact path='/login' component={Login} />
<Route exact path='/new-user' component={CreateAccount} />
<Route render={props => <AuthenticationRouter {...props} />}
</Switch>
</Router>
);
};
const AuthenticatedRouter = (props) => {
if( props.userIsAuthenticated ) {
return (
<Router>
<Switch>
<Route exact path='/' component={Store} />
<Route
exact
path='/account'
component={Account}
/>
<Route
exact
path='/shipping'
component={Shipping}
/>
<Route
exact
path='/checkout'
component={Checkout}
/>
<Route render={() => (<h2>Not Found</h2>)} />
</Switch>
</Router>
);
}
return (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
);
};
export default AppRouter;
关于javascript - 我可以在 React Router 的 Switch 内使用高阶私有(private)路由组件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56811107/