react-router - React-Router 5 - BrowserRouter 仅在不匹配时才会在页面刷新时进行后备重定向
问题描述
到目前为止/home
,在刷新页面时,如果路由器无法匹配,我还没有找到重定向到的方法。如果您打开Bar
并刷新,您将始终转到/home
而不是Bar
. 没有redirect
您可以刷新并继续使用Bar
。有没有办法知道何时Switch
无法匹配任何定义的路线?
<Switch>
<Route path={ '/foo' }>
<Foo />
</Route>
<Route path={ '/bar' }>
<Bar />
</Route>
<Route path={ '/home' }>
<Home />
</Route>
<Route path={ '/' }>
<Redirect to={ '/home' } />
</Route>
</Switch>
解决方案
您可以定义 NotFoundComponent 或手动重定向到 '/' url。尝试像这样定义路由,然后您可以在 URL 无效时重定向到 /404 页面。我认为这将是更好的解决方案。
<Switch>
<Route path="/home" component={Home} />
<Route path="/foo" component={Foo} />
<Route path="/bar" component={Bar} />
<Route path="/404" component={NotFoundComponent} />
<Redirect to="/404" />
</Switch>
在你的情况下
<Switch>
<Route path="/home" component={Home} />
<Route path="/foo" component={Foo} />
<Route path="/bar" component={Bar} />
<Redirect to="/home" />
</Switch>
希望这能帮助你理解!
推荐阅读
- python - 声明一个函数来对数据进行指数平滑处理
- python - 从 __init__ 中的 Python 子模块导入方法,但不是子模块本身
- c# - 我想为此控制器创建 Xunit 测试。我怎样才能做到这一点
- neo4j - 如何使用 js2neo 驱动程序在 javascript 中建立与 Neo4j 图形数据库的连接
- java - 如何在 Eclipse/Netbeans IDE 中为 Java NLP 项目添加 stanford corenlp 库?
- performance - 在 python 中 multiprocessing.pool.starmap() 后仅使用 20% 的 CPU
- c++ - 当两个模板参数属于同一类型时,如何执行部分特化?
- r - 基于文件输入的条件动作(闪亮)
- python - 用抽象类建模多对多关系(错误:fields.E331)
- java - Spring 引导应用程序无法“自动装配”作为新线程代理的服务类