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

为何依赖项未变化时useEffect仍执行?React路由场景问题

解决方案

问题出在useEffect的执行机制上:组件挂载时,不管依赖项是否变化,useEffect都会默认执行一次。当你通过React Router切换页面再返回时,当前组件会重新挂载,因此即使showContent还是初始的false,滚动操作依然会触发。

你可以通过useRef标记首次渲染,只在showContent主动变化时执行滚动,修改后的代码如下:

import { useState, useEffect, useRef } from 'react';

// ...你的组件逻辑
const [showContent, setShowContent] = useState(false);
const isFirstRender = useRef(true);

useEffect(() => {
  // 首次渲染直接跳过滚动逻辑
  if (isFirstRender.current) {
    isFirstRender.current = false;
    return;
  }

  // 仅当showContent状态变化时执行滚动
  window.scrollTo({top: 1400, left: 0, behavior: 'smooth' });
  console.log(showContent);
}, [showContent]);

<button onClick={() => setShowContent(!showContent)}>
  {showContent ? "Show Less" : "Show More"}
</button>

逻辑说明

  • useRef的current属性会在组件整个生命周期中保持引用不变,用来记录是否是首次渲染。
  • 组件挂载后第一次进入useEffect时,会将isFirstRender.current设为false并直接返回,不执行滚动。
  • 后续只有当showContent通过按钮点击发生变化时,才会触发滚动操作。

如果你的showContent是通过Context管理的,只需将useState替换为useContext获取状态,其余逻辑保持一致即可。

内容的提问来源于stack exchange,提问作者JayK

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 18:12:12