为什么 useEffect 不会在 window.location.pathname 更改时运行? [英] Why useEffect doesn't run on window.location.pathname changes?

查看:37
本文介绍了为什么 useEffect 不会在 window.location.pathname 更改时运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 useEffect 不在 window.location.pathname 更改时运行?我只记录了一次 loc.

Why useEffect doesn't run on window.location.pathname changes? I get loc logged only once.

如何在没有任何附加库的情况下在路径名更改时运行 useEffect?

How can I make to run useEffect when pathname changes without any additional libraries?

  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;
};

然后在你的组件中像这样使用它:

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.

这篇关于为什么 useEffect 不会在 window.location.pathname 更改时运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆