環境
react-router-dom は v4.3.1 でした。
v5 is fully backwards compatible with 4.x
とあるので、多分 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]);
って感じで書けたんですが、遷移元も欲しいな〜と思っていたら、教えてくださいました。多謝。