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

类组件转React Hooks后getFloorplan报调用栈溢出错误如何解决

问题根因

报错是命名冲突导致的无限递归调用:

  • 你从../redux/actions导入的getFloorplan、getGraph、changeActiveCamera是Redux的action创建函数
  • 你自己定义的、用来包装dispatch的函数也用了完全相同的名字,函数内部调用getFloorplan(site)的时候,访问到的是你刚定义的这个函数本身,而不是导入的action创建函数,就会无限递归触发调用,最后触发栈溢出报错。
修正方案

导入时给action创建函数加别名避免命名冲突,同时补全缺失的useDispatch调用、以及realGraph的useSelector取值即可:

import { useSelector, useDispatch } from 'react-redux'
// 导入时给action创建函数加别名,避免和后续封装的dispatch方法重名
import {
  getGraph as getGraphAction,
  getFloorplan as getFloorplanAction,
  changeActiveCamera as changeActiveCameraAction,
} from "../redux/actions";

// 组件内部代码
const dispatch = useDispatch()
const currentSite = useSelector((state) => state.selection.currentSite);
const currentCamera = useSelector((state) => state.selection.currentCamera);
// 补充你之前漏掉的realGraph取值,xxx替换成你redux里realGraph所在的reducer字段名
const realGraph = useSelector((state) => state.xxx.realGraph)

// 封装的dispatch方法可以保留原名,内部调用的是带别名的action创建函数
const getFloorplan = (site) => dispatch(getFloorplanAction(site));
const getGraph = (site) => dispatch(getGraphAction(site));
const changeActiveCamera = (site, id) => dispatch(changeActiveCameraAction(site, id));

const loadGraph = () => {
  if (currentSite) {
    getFloorplan(currentSite.identif).then(() => {
      console.log("Fetched floorplan");

      getGraph(currentSite.identif).then(() => {
        console.log("Fetched model", realGraph.model);

        // new camera-related node & link status
        if (currentCamera) {
          changeActiveCamera(
            currentSite.identif,
            currentCamera.identif
          );
        }
      });
    });
  }
};
补充注意点
  • 如果你用redux-thunk处理异步action,确保thunk中间件已经正确配置,才可以在dispatch之后调用.then()方法
  • 要是loadGraph是在useEffect里调用的,记得把用到的依赖(currentSite、currentCamera等)放到useEffect的依赖数组里,避免闭包陷阱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:18:02