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

如何封装使用useDispatch、useHistory的可复用全局scheduleShortcut函数?

解决方案

正确的自定义Hook写法

你需要让自定义Hook返回可执行的函数,而不是直接在Hook体内运行跳转和dispatch逻辑,这样既符合Hook调用规则,又能在回调里使用:

import { useHistory } from 'react-router-dom';
import { useDispatch } from 'react-redux';
// 替换为你项目中对应的action引入路径
import { jobGanttFocus, focusJobScheduleFilter, toggleScheduleView } from '@/store/actions';

export const useScheduleShortcut = () => {
  const history = useHistory();
  const dispatch = useDispatch();

  // 将业务逻辑封装为内部函数返回
  const scheduleShortcut = (jobId: number) => {
    dispatch(jobGanttFocus(jobId));
    dispatch(focusJobScheduleFilter(jobId));
    dispatch(toggleScheduleView('jobs'));
    history.push('/schedule');
  };

  return scheduleShortcut;
};

组件内使用方式

在组件顶层调用Hook获取绑定好依赖的方法,再传入回调即可,完全符合Hook调用规则:

// 组件渲染顶层调用Hook
const scheduleShortcut = useScheduleShortcut();

// 给组件传参时直接使用返回的普通函数
<Roster
  jobId={job.id}
  assignWorkers={canAssignWorker ? handleAssignWorkers : undefined}
  scheduleShortcut={() => scheduleShortcut(jobId)}
/>

兼容说明

如果你的项目已经升级到React Router v6,把useHistory替换为useNavigate,对应跳转逻辑修改为navigate('/schedule')即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:27:07