react-router的redirect的问题

代码如下

<Router>
  <Route path="/wx/home" component={Home} />
  <Route path="/wx/search/" component={Search} />
  
  <Route path="/ali/list/" component={List} />
  <Route path="/ali/detail/" component={Detail} />
  
  <Route path="/tt/react" component={() => <div>React</div>} />
  <Route path="/tt/next" component={() => <div>Next</div>} />
  <Route path="/tt/egg" component={() => <div>Egg</div>} />

  <Redirect from="/wx" to="/wx/home"></Redirect>
  <Redirect from="/ali" to="/ali/list"></Redirect>
  <Redirect to="/tt/react"></Redirect>
  <Redirect from="/" to="/wx"></Redirect>
</Router>;

需求是

  • 路由是/重定向到/wx
  • 路由是/wx重定向到/wx/home
  • 路由是/ali重定向到/ali/list
  • 路由是/tt重定向到/tt/react

但是上面的写法总是最后一个redirect有效,这种需求应该怎么设置路由?

阅读 4.1k
1 个回答

因为/默认match所有路径,所以<Redirect from="/" to="/wx"></Redirect>这一句总是执行。
要想只match/需要添加exact 标识,变成 <Redirect exact from="/" to="/wx"></Redirect>.
(参考 exact 部分:https://reacttraining.com/react-router/web/api/Redirect

还有<Router>里面应该用<Switch>包裹<Route>,这样才只match一个符合的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题