react-routerで、存在しないパスへのアクセスを全て/dashboard
へリダイレクトしたい、などのような実装をするときには以下のようなワイルドカード指定を使ったりします
routes.js
<div id="app">
<Route path="/dashboard" component={DashboardComponent} />
<Route path="/login" component={LoginComponent} />
<Redirect from="*" to="/dashboard" />
</div>
ですが、このままだとreact-routerはWarning: You tried to redirect to the same route you're currently on: "/dashboard"
というエラーを吐きます。
これは、/dashboard
というパスもワイルドカードによって認識されてしまい、同じパスへのリダイレクトが二度起こってしまうからです。
これを解決するには、定義されているルーティングをSwitch
を使って囲うだけです。
<div id="app">
+ <Switch>
<Route path="/dashboard" component={DashboardComponent} />
<Route path="/login" component={LoginComponent} />
<Redirect from="*" to="/dashboard" />
+ </Switch>
</div>
参考: https://github.com/guyellis/learn/issues/205#issuecomment-334965112