使用react-router-dom重定向匹配的参数不起作用

问题描述 投票:0回答:1

我正在使用react-router-dom:4.3.0-rc.3。 路线组件

<Switch>
  <Redirect from='/p/:userId' to='/p/:userId/main' />
  <Route path="/p/:userId/main" component={Main} />
</Switch>

当我得到一个网址/p/123456它重定向到/p/:userId/main并丢失userId。 我很困惑。在官方网站上,我无法得到答案。

reactjs react-router react-router-v4 react-router-dom
1个回答
1
投票

<Redirect>不进行任何模式编译。您必须为其指定要重定向到的实际URI。

我将采用的方法是使用<Route>而不是<Redirect>进行匹配,然后使用解析的param来构建重定向URI。

<Route path="/p/:userId" render={({ match }) => (
  <Redirect to={`/p/${match.params.userId}/main`} />
)} />
© www.soinside.com 2019 - 2024. All rights reserved.