使用react 16.13.1和react路由器5.1.2处理客户端路由,并存在一些路由问题.
首先,我有一个Switch组件,它有几个子Route组件(如下面所示),并且一切都按照预期进行路由。与我的任何特定路径不匹配的路径都会通过fall路由。
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/old-match">
<Redirect to="/will-match" />
</Route>
<Route path="/will-match">
<WillMatch />
</Route>
<Route path="*">
<NoMatch />
</Route>
</Switch>接下来,我想让一些路由是私有的,这样只有登录用户才能访问它们。我见过几个自定义PrivateRoute组件的例子,但是当我实现它们时,我似乎每次都会遇到同样的问题。在私有路由之后定义的任何路由都不会成功匹配。我编写了一个简化的代码版本,它使用一个isAuthenticated变量内联地呈现一些条件组件,如下所示:
const isAuthenticated = true;
<Switch>
<Route exact path="/">
<Home />
</Route>
{isAuthenticated && (
<>
<Route path="/old-match">
<Redirect to="/will-match" />
</Route>
<Route path="/will-match">
<WillMatch />
</Route>
</>
)}
<Route path="*">
<NoMatch />
</Route>
</Switch>捕获所有路径永远不会匹配,因为它是在私有片段之后。我在这里做错什么了?我在https://codesandbox.io/s/react-router-test-fzl22有一个简化示例的沙箱。任何帮助都是非常感谢的。
发布于 2020-03-31 21:35:52
React片段标记正在破坏Switch语句。如果将代码重构为:
<Switch>
<Route exact path="/">
<Home />
</Route>
{isAuthenticated && (
<Route path="/old-match">
<Redirect to="/will-match" />
</Route>
)}
{isAuthenticated && (
<Route path="/will-match">
<WillMatch />
</Route>
)}
<Route path="*">
<NoMatch />
</Route>
</Switch>密码很好用。
您可以在沙箱这里的分叉中看到这一点。
发布于 2020-03-31 21:36:34
尝试使用三元运算符代替And操作。
const isAuthenticated =真;
<Switch>
<Route exact path="/">
<Home />
</Route>
{isAuthenticated ? (
<>
<Route path="/old-match">
<Redirect to="/will-match" />
</Route>
<Route path="/will-match">
<WillMatch />
</Route>
</>
:
<Route path="*">
<NoMatch />
</Route>
)
https://stackoverflow.com/questions/60960047
复制相似问题