3
3

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 5 years have passed since last update.

react router v4 他のコンポーネントで発生させたイベントでリロードさせずに<Link>したい時

Posted at

通常であればユーザーが<Link>を押して、それぞれ<Route>に割り当てられているコンポーネントを表示するが、コンポーネントの発生させるイベントに連動して<Route>に割り当てられているコンポーネントをプログラム的に遷移表示(<Link>を押した時と同じ挙動)にさせる場合

方法1 - 囲む

イベントが発生するコンポーネントを<Link>で囲む

<link to="/path">
  <SomeComponent onTouchTap={() => console.log("event!")}>
</link>

これだとイベントの内容に応じてリンクさせるかどうかの判断が出来ない

方法2 - pushする

handler(){
  //...何らかの処理
  //...
  if(ok){
    this.props.history.push("/path")
  }
}
//...
//...
<SomeComponent onTouchTap={() => this.handler}>

これだとサーバーに/pathがヒットしてしまう(結果、リロードする形になる)

方法3(解決方法)

handler(){
  //...何らかの処理
  //...
  if(ok){
    const location = {
      pathname: "/path",
      state: { fromDashboard: true }
    }
    this.props.history.push(location)
  }
}
//...
//...
<SomeComponent onTouchTap={() => this.handler}>

locationオブジェクトをpushする
こうする事により<Link>をクリックしたようにサーバーにヒットせずに画面遷移がプログラム的に出来る

Banners_and_Alerts_and_React_Router__Declarative_Routing_for_React_js.png
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?