如何在反应中没有页面刷新的情况下侦听页面url更改?



我在页面上有一些面包屑。当我做replaceState时,我看到url改变了,这没有问题,但我无法在react组件中捕获url改变,我已经尝试过了,但没有意义,它只在组件挂载时工作一次。

const usePath = () => {
const [path, pathSet] = useState(window.location.pathname);
const listenToPopstate = () => {
const winPath = window.location.pathname;
pathSet(winPath);
};
useEffect(() => {
window.addEventListener("locationchange", listenToPopstate);
return () => {
window.removeEventListener("locationchange", listenToPopstate);
};
}, []);
return path;
};

const Breadcrumb = () => {
const [state, stateSet] = useState(false);
const path = usePath();
useEffect(() => {
path.indexOf('StoreSelection') > -1 && stateSet(true)
}, [path]);
return (
<ol className="breadcrumb" style={breadcrumb}>
<li key="1" className="breadcrumb-item align-items-center">
{state ? 'AAA' : 'BBB'}
</li>
</ol>
);
}

我想你会发现实例化一个history对象并使用它来监听对你来说会更容易。

历史
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
const usePath = () => {
const [path, pathSet] = useState(history.location.pathname);
const listener = (location, action) => {
pathSet(location.pathname);
};
useEffect(() => {
const unlisten = history.listen(listener);
return unlisten;
}, []);
return path;
};

最新更新