1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

react-router-domでURLは変わっているのに画面遷移がされなかった時の解決法

Posted at

現在Reactの学習を始め、ReactRouterを使ってルーティングを指定しましたが、思ったように動かなかったため、その時の解決法を記録として残しておきます。

 概要

アプリケーションは基礎中の基礎であるTodolistです。

ファイル名

送信ボタンをクリックするとリスト一覧に表示される(redux使用)→一覧をクリックすると詳細ページに遷移します。

問題点

一覧をクリックすると、URLは変わるのに画面は変わらないという状況
その時のコードが以下のとおりです。(該当箇所のみを抜粋しています。)

変更前

const App = () => (
  <BrowserRouter>
    <Switch>
      <Route path="/" component={ToDoList} />
      <Route path="/to_dos/:id" component={ToDoDetail} />
    </Switch>
  </BrowserRouter>
  );

解決方法

exactをRouteに指定する

exactは「正確な」という意味があり、 ドキュメントには以下のように書かれています。

When true, will only match if the path matches the location.pathname exactly

REACT ROUTERドキュメント

exactがtrueで、pathと、locationオブジェクトのpathnameプロパティの値が正確に一致する場合に指定したコンポーネントを返してくれるみたいです。

上記の、思うように動かなかったルーティング指定の場合、"/to_dos/:id"に "/"が含まれるため、両者ともルーティング先と見なされるため思うような挙動をしてくれませんでした。

変更後
<Route exact path="/" component={ToDoList} />
<Route path="/to_dos/:id" component={ToDoDetail} />

デフォルトでexactはfalseのため、明記することでtrueとして、正確なパスの場合のみ該当のコンポーネントを返してくれるようになります。

これで無事、詳細ページと遷移することができました!

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?