未在事件监听器中获取更新的路径名值

问题描述 投票:0回答:1

我在效果中添加了一个滚动事件侦听器,这样当到达某一部分时,url 就会更改为不同的部分。

React.useEffect(() => {
  window.addEventListener('scroll', handleScroll);

  return () => {
    window.removeEventListener('scroll', handleScroll);
  };
}, [])

这是函数

handleScroll

const handleScroll = () => {
  const urlKey = `/${section}/${url}`;

  if (pathname !== urlKey) {
    history.replace(urlKey);
  }
}

section
url
的值是在其他地方获取的,并且它们输出正确。问题是里面的
handleScroll
pathname
总是一样的。我不明白如何解决它。请给我提示。

reactjs react-router
1个回答
0
投票

尝试将

handleScroll
函数包装在
useCallback
中,每当依赖项之一(
section
url
pathname
)发生更改时,这都会创建该函数的新实例:

const handleScroll = React.useCallback(
  () => {
    const urlKey = `/${section}/${url}`;

    if (pathname !== urlKey) {
      history.replace(urlKey);
  },
  [section, url, pathname]
);

然后,将回调添加到

useEffect
的依赖项中,以便每当有
handleScroll
的新实例时更新事件侦听器:

React.useEffect(
  () => {
    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, 
  [handleScroll]
);
© www.soinside.com 2019 - 2024. All rights reserved.