LoginSignup
2
1

More than 5 years have passed since last update.

You tried to redirect to the same route you're currently on の解決法

Last updated at Posted at 2018-01-06

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

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1