我们正在更换 react-router-dom
s HashRouter
与 BrowserRouter
并希望将旧路由重定向到新路由。
我标记了 nginx
因为我不介意在那里进行重定向。 :)
假设我们有一条旧路由 /#/users
和 /#/users:id
:它们应该匹配并重定向到 /users
和 /users/:id
.
到目前为止,我尝试过( react-router-dom v5.0.1
):
<Router>
<Switch>
<Route path='/users' component={UsersComponent} />
<Route path='/users/:id' component={UsersDashComponent} />
</Switch>
<Redirect from='/#/users' to '/users' />
<Redirect from='/#/users/:id' to='/users/:id' />
</Router>
第一条路由匹配并重定向正常。第二个(使用
id
)有问题。当我导航到 /#/users/123
它重定向到 /users/:id
.它正在取代实际的 123
与 :id
.这是路线的两个例子。我们还有更多需要重定向的参数。
最佳答案
我认为导航你正在使用这样的东西,
<Link to="/#/users" />
<Link to="/#/users/123" />
根据 docs ,
A
<Router>
that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL.
使用时
HashRouter
您不需要预先添加 #
手动 React 路由器自动添加 #
在 URL
所以你的路线必须是,
import { HashRouter } from 'react-router-dom'
<HashRouter>
<Switch>
<Route exact path='/users' component={UsersComponent} />
<Route exact path='/users/:id' component={UsersDashComponent} />
</Switch>
</HashRouter>
链接应该是,
<Link to="/users" />
<Link to="/users/123" />
现在来回答你的问题,如何更换
HashRouter
与 BrowserRouter
?要做到这一点,你只需要这样做,
import { BrowserRouter } from 'react-router-dom'
<BrowserRouter>
<Switch>
<Redirect from='/#/users' to '/users' />
<Redirect from='/#users/:id' to='/users/:id' />
<Route exact path='/users' component={UsersComponent} />
<Route exact path='/users/:id' component={UsersDashComponent} />
</Switch>
</BrowserRouter>
你的链接应该是一样的。
注:也看看我加了
exact
至 route
,它将匹配精确的 path
.
关于reactjs - 如何将旧的 react-router HashRouter(带有 #)重定向到 BrowserRouter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56981230/