没有匹配到路由时如何重定向?

How do I redirect when no route is matched?

我想做这样的事情,如果没有匹配的路由,我会立即重定向到“/”。使用下面的代码,当我遇到不存在的路径时,我得到 Nothing was returned from render

    <Switch>
      <Route exact path="/" component={UnAuth} />
      <PrivateRoute exact path="/:contentId" component={Content} />
      <Redirect to="/" />
   // <Redirect from='*' to='/' /> doesn't work as well
    </Switch>

如果你想要一个 "catch all route" 将重定向到任何地方 ("/")

因此您将首先创建一个 "catch all" 路线

<Switch>
  <Route exact path="/" component={UnAuth} />
  <PrivateRoute exact path="/:contentId" component={Content} />
  //...all of your routes here

  // this route will catch any route that wasnt matched in previous routes
  <Route component={RedirectToMain}/> 

</Switch>

以及将获取所有路由和重定向的组件: 它只会重定向到 / 如果你想要更多的逻辑,你可以创建一个 class 来处理其他任何事情。

const RedirectToMain = _ => {
    return (
        <Redirect to="/" />
    );
}