首页 > 解决方案 > 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>

标签: react-router

解决方案


您可以定义 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>

希望这能帮助你理解!


推荐阅读