LoginSignup
1
0

More than 3 years have passed since last update.

react-router でページ遷移をトリガーにて何かする(prevPathname も取る)

Posted at

環境

react-router-dom は v4.3.1 でした。

v5 is fully backwards compatible with 4.x

https://reacttraining.com/blog/react-router-v5/#tldr

とあるので、多分 v5 でも動きます。多分。

まとめ

react-router でページ遷移をトリガーになんらかの処理をしたかった。
しかも、遷移先のページだけでなく遷移元のページの pathname も取りたかった。

以下コード。

import React, { useRef } from "react";
import { withRouter } from "react-router-dom";

const App = withRouter((props) => {
  const prevPathnameRef = useRef<Location["pathname"]>();
  const prevPathname = prevPathnameRef.current;
  useEffect(() => {
    prevPathnameRef.current = location.pathname;

    // ここに処理を書く
    // prevPathname から location.pathname へページ遷移
  }, [location.pathname]);

  return <>{/* Routes */}</>;
});

遷移先の pathname だけだったら useEffect(() => { /* location.pathname へページ遷移 */ }, [location.pathname]); って感じで書けたんですが、遷移元も欲しいな〜と思っていたら、教えてくださいました。多謝。

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