为什么 useEffect 不会在 window.location.pathname 更改时运行?

2024-01-06

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(使用前将#替换为@)

为什么 useEffect 不会在 window.location.pathname 更改时运行? 的相关文章

随机推荐