Create a hook, something like:
const useReactPath = () => {
const [path, setPath] = React.useState(window.location.pathname);
const listenToPopstate = () => {
const winPath = window.location.pathname;
setPath(winPath);
};
React.useEffect(() => {
window.addEventListener("popstate", listenToPopstate);
return () => {
window.removeEventListener("popstate", listenToPopstate);
};
}, []);
return path;
};
Then in your component use it like this:
const path = useReactPath();
React.useEffect(() => {
// do something when path changes ...
}, [path]);
Of course you'll have to do this in a top component.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…