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

react-router-dom的history对象是否需要加入useEffect的依赖数组?

useEffect中history依赖项必填性解答

结论

是,history属于必须加入useEffect依赖数组的必填项,原因如下:

  • 符合React Hook的官方规则:eslint-plugin-react-hooks 自带的 exhaustive-deps 校验规则要求,所有在useEffect回调内部引用的外部可变变量,都必须加入依赖数组。你在回调中调用了history.push方法,history属于外部引用变量,满足依赖加入条件。
  • 不会引发额外执行问题:react-router-dom v5及以上的正式版本中,useHistory返回的history对象是稳定引用,组件重渲染时不会生成新的history实例,因此把它加入依赖数组不会触发useEffect的意外重复执行,没有性能负担。

你当前代码的两个隐藏问题

  1. 不要直接给useEffect传async函数作为回调
    async函数会默认返回Promise对象,但useEffect的回调仅支持返回清理函数,该写法会导致清理逻辑无法正常执行,存在内存泄漏风险。
  2. 依赖数组漏加了id参数
    你调用asyncFetchData时用到了props传入的id,该变量也属于外部引用,必须加入依赖数组,否则函数永远只能拿到首次渲染时的id值。

修正后的代码示例

import { useEffect } from 'react';
import { useHistory } from 'react-router-dom';

const Component = ({ id }) => {
  const history = useHistory();

  useEffect(() => {
    // 在useEffect内部定义异步函数再调用
    const handleFetch = async () => {
      await asyncFetchData(id);
      history.push("/homepage");
    };
    handleFetch();
  }, [id, history]); // 补全所有依赖项

  return (
    <div>
      <Button onClick={handleClick}>Click</Button>
    </div>
  );
};

export default Component;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:36:06