Why 使用效果不运行window.location.pathname
变化?我明白了loc
仅记录一次。
我怎样才能运行使用效果当路径名更改而没有任何附加库时?
useEffect(() => {
const loc = window.location.pathname
console.log({ loc })
}, [window.location.pathname])
创建一个钩子,例如:
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;
};
然后在你的组件中像这样使用它:
const path = useReactPath();
React.useEffect(() => {
// do something when path changes ...
}, [path]);
当然,您必须在顶部组件中执行此操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)