实现react-router下,非法路径访问跳转首页

作者 happyWang 日期 2017-12-04 Views
实现react-router下,非法路径访问跳转首页

react-router下,基于Switch,可以实现针对未匹配的路由调用指定的component来展现

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Switch>

现在的需求是:在发现有未匹配的路由时,自动跳转到首页 如果把上面的代码改成:

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={Home}/>
</Switch>

这个可以实现的时,未匹配的路由展现首页的内容,可是当前的url还是那个未被匹配的路由。这样的显示就会有点怪异。

针对这个问题,可以使用react-router里面的另外一个组件Redirect

基于Redirect新建如下组件:

const RouteFallback = (props) => {
    console.log('route fallback with location: ', props.location);
    return <Redirect to={ {
        pathname: '/',
        from: props.location
    }} />
}

再重新调整Switch:

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={RouteFallback}/>
</Switch>

这样就能实现针对非法路径的自动跳转首页的功能了