【发布时间】:2019-06-28 17:35:08
【问题描述】:
我正在尝试设置 Router 以使用自定义 PrivateRoute 组件,这些组件等效于官方 react-router 文档中给出的 example。问题是我还想使用包罗万象的 404 路由,所以我想我也需要使用 Switch 组件,如文档中的 this example 所示。
这里有一个冲突,因为 Switch 的 docs 声明 Switch 组件的子级必须是 Route 组件,而在 this issue 中,团队声明在Switch 不受支持,即使它恰好可以工作。
我已经创建了高阶路由,目前正在 Switch 中使用它们,它似乎可以正常工作,但这不会通过我公司的代码审查,因为它使用了不受支持的 API,可能会中断随时。我想知道是否有完全支持的方式来使用高阶路由和包罗万象的路由。
我正在考虑尝试创建一个 404 路由,而不需要使用 Switch,或者使用常规的 Route 组件,而是将传递给 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;
【问题讨论】:
-
您想创建一个“默认”(404) 路由,但不使用
Switch? -
你能澄清你的问题吗?我认为您需要交换机,因为交换机的最后一条路由应该是
default路由(例如:404)。Switch的工作方式是,如果路径不匹配任何先前的路由,它将呈现最后一个路由。如果没有Switch组件,您将始终呈现 404 组件。 -
Switch是如何成为不受支持的 API 的? Switch Docs -
@technogeek1995 使用非路由组件作为
Switch的子级不受支持。 docs -
@KevinWaddle 我现在明白了。我想我创造了你想要的东西
标签: javascript reactjs react-router-dom