You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中条件未满足时滚动函数仍执行的问题求助

仅在根路径触发滚动背景变化函数的解决方案

你的问题出在没有清理滚动事件监听器:当路由处于/时,你给document添加了scroll事件的监听器,但切换到其他页面后,这个监听器并没有被移除,所以滚动页面时依然会执行changeBackground函数。

下面是修复后的代码:

const location = useLocation();
const [colorBackground, setColorBackground] = useState(false);

// 把滚动逻辑提取为独立函数
const changeBackground = () => {
  setColorBackground(window.scrollY >= 80);
};

useEffect(() => {
  if (location.pathname === '/') {
    // 进入根路径时添加监听器
    document.addEventListener('scroll', changeBackground);
    // 初始化时同步一次滚动状态
    changeBackground();
  } else {
    // 离开根路径时强制设置背景为true,并移除监听器
    setColorBackground(true);
    document.removeEventListener('scroll', changeBackground);
  }

  // 组件卸载或路由变化时,确保移除监听器(兜底清理)
  return () => {
    document.removeEventListener('scroll', changeBackground);
  };
}, [location.pathname]);

关键修改说明:

  • 将changeBackground提取到useEffect外部,保证每次移除监听器时能匹配到同一个函数实例(如果在useEffect内部定义,每次渲染都会生成新函数,旧监听器无法被正确移除)
  • 新增清理函数(useEffect的返回值):不管组件卸载还是路由切换,都会自动移除滚动监听器,避免内存泄漏和无效触发
  • 进入根路径时主动调用一次changeBackground,避免初始状态和当前滚动位置不匹配
  • 离开根路径时主动移除监听器,同时强制设置背景状态为true

内容的提问来源于stack exchange,提问作者Tobias Schleiss-Andreassen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:24:08