[英]global React functions that utilize hooks
I have a function called scheduleShortcut
that gets used in a couple places throughout an application.我有一个名为
scheduleShortcut
的函数,它在整个应用程序的几个地方使用。 Initially, this function was local to the specific components but since it is being used multiple times, I want to refactor this function into a global function.最初,此函数是特定组件的本地函数,但由于它被多次使用,我想将此函数重构为全局函数。
At first, I tried to do the following:起初,我尝试执行以下操作:
const history = useHistory();
const dispatch = useDispatch();
export const scheduleShortcut = (jobId: number) => {
dispatch(jobGanttFocus(jobId));
dispatch(focusJobScheduleFilter(jobId));
dispatch(toggleScheduleView('jobs'));
history.push('/schedule');
};
However, when I do this, I get an error that says I can't use useHistory or useDispatch unless they are inside a React component or a custom hook.但是,当我这样做时,我收到一个错误,提示我不能使用 useHistory 或 useDispatch,除非它们在 React 组件或自定义钩子中。 Then, I tried to convert scheduleShortcut into a custom hook in the following way:
然后,我尝试通过以下方式将 scheduleShortcut 转换为自定义钩子:
export const useScheduleShortcut = (jobId: number) => {
const history = useHistory();
const dispatch = useDispatch();
dispatch(jobGanttFocus(jobId));
dispatch(focusJobScheduleFilter(jobId));
dispatch(toggleScheduleView('jobs'));
history.push('/schedule');
};
This allowed me to utilize useDispatch and useHistory.这让我可以使用 useDispatch 和 useHistory。 However, when I try to call this function inside the specific components I need it in, I get a similar error.
但是,当我尝试在需要它的特定组件中调用此函数时,会出现类似的错误。 Basically, it says that I cannot use my custom hook (ie
useScheduleShortcut
) inside a callback.基本上,它说我不能在回调中使用我的自定义钩子(即
useScheduleShortcut
)。
<Roster
jobId={job.id}
assignWorkers={canAssignWorker ? handleAssignWorkers : undefined}
scheduleShortcut={() => useScheduleShortcut(jobId)}
/>
Is there a way I can get around these errors and use scheduleShortcut as a recyclable function?有没有办法解决这些错误并将 scheduleShortcut 用作可回收功能? Or is this in fact not possible since I am using the hooks?
或者这实际上是不可能的,因为我使用的是钩子?
Hooks in fact must be called on top level, you are breaking that rule实际上必须在顶层调用 Hooks,您违反了该规则
You could expose(return) a function from hook that could be called as callback afterwards.您可以从钩子中公开(返回)一个函数,之后可以将其作为回调调用。
ie IE
export const useScheduleShortcut = () => {
const history = useHistory()
const dispatch = useDispatch()
const dispatchScheduleShortcut = (jobId) => {
dispatch(jobGanttFocus(jobId))
dispatch(focusJobScheduleFilter(jobId))
dispatch(toggleScheduleView('jobs'))
history.push('/schedule')
}
return {
dispatchScheduleShortcut
}
};
and then use it as然后将其用作
const { dispatchScheduleShortcut } = useScheduleShortcut()
return (
<Roster
jobId={job.id}
assignWorkers={canAssignWorker ? handleAssignWorkers : undefined}
scheduleShortcut={() => dispatchScheduleShortcut(jobId)}
/>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.