代码如下
<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有效,这种需求应该怎么设置路由?
因为
/
默认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一个符合的。