带钩子的 redux-saga 不工作,无效的钩子调用
redux-saga with hooks not working, invalid hook call
我正在尝试使带有钩子的 redux-saga 正常工作,但我找不到使它按我想要的方式工作的方法。控制台告诉我,我只需要在我的功能主体组件中执行 hook,我确实这样做了,但它不起作用。
我尝试过的事情:
- 调用组件中的钩子
- 在 formik 的 onSubmit 回调中调用钩子
- 尝试 return 回调以避免在
core/notifications/index.ts
中即时调用我的自定义挂钩
这是钩子:
function useUpdateNotifications(subscriptions: FormatedSubscription) {
const dispatch = useDispatch();
const formatSubscriptions = valuesIn(subscriptions);
return () =>
dispatch(Events.updateNotifications(formatSubscriptions as Subscription[]));
}
我称之为的地方:
const formik = useFormik({
initialValues: formatedValues,
onSubmit: (values: FormatedSubscription) => {
Core.updateNotifications(values);
}
});
您可以在此处找到具有相同问题的沙箱 https://codesandbox.io/s/hook-formik-sagas-issues-3pq62
core/notifications/index.tsx
我的通知挂钩和所有逻辑都在那里。我有我的 sagas、选择器,然后我使用 useDispatch(useSelector 等)创建我的钩子。例如,当我提交我的 formik 表单时,钩子 useUpdateNotifications
(用于发送插入我的一个 sagas 的事件)在 src/index.tsx
中被调用。但是当我提交我的表单时,控制台显示一个警告告诉我应该在函数组件的主体内部调用挂钩。这正是我所做的。
你有什么建议吗?
然后我找到了解决方案,方法和原因。以下是解释:
- 我用一个参数调用我的钩子,而不是通过我的调度将它推迟到我的回调内部。当然,根据文档,我们需要先调用 de hook,我的错误是对此的误解。我带来了这个解决方案,现在效果很好:
function useUpdateNotifications() {
const dispatch = useDispatch();
return (items: FormatedSubscription) => {
const formatSubscriptions = valuesIn(items);
dispatch(Events.updateNotifications(formatSubscriptions as Subscription[]));
};
}
而且我可以简单地调用它而不会出现打字稿错误询问我 "Expect 1 argument but got 0" :
const updateNotifications = Core.updateNotifications();
updateNotifications(notifications);
希望对以后的人有所帮助。
我正在尝试使带有钩子的 redux-saga 正常工作,但我找不到使它按我想要的方式工作的方法。控制台告诉我,我只需要在我的功能主体组件中执行 hook,我确实这样做了,但它不起作用。
我尝试过的事情:
- 调用组件中的钩子
- 在 formik 的 onSubmit 回调中调用钩子
- 尝试 return 回调以避免在
core/notifications/index.ts
中即时调用我的自定义挂钩
这是钩子:
function useUpdateNotifications(subscriptions: FormatedSubscription) {
const dispatch = useDispatch();
const formatSubscriptions = valuesIn(subscriptions);
return () =>
dispatch(Events.updateNotifications(formatSubscriptions as Subscription[]));
}
我称之为的地方:
const formik = useFormik({
initialValues: formatedValues,
onSubmit: (values: FormatedSubscription) => {
Core.updateNotifications(values);
}
});
您可以在此处找到具有相同问题的沙箱 https://codesandbox.io/s/hook-formik-sagas-issues-3pq62
core/notifications/index.tsx
我的通知挂钩和所有逻辑都在那里。我有我的 sagas、选择器,然后我使用 useDispatch(useSelector 等)创建我的钩子。例如,当我提交我的 formik 表单时,钩子 useUpdateNotifications
(用于发送插入我的一个 sagas 的事件)在 src/index.tsx
中被调用。但是当我提交我的表单时,控制台显示一个警告告诉我应该在函数组件的主体内部调用挂钩。这正是我所做的。
你有什么建议吗?
然后我找到了解决方案,方法和原因。以下是解释:
- 我用一个参数调用我的钩子,而不是通过我的调度将它推迟到我的回调内部。当然,根据文档,我们需要先调用 de hook,我的错误是对此的误解。我带来了这个解决方案,现在效果很好:
function useUpdateNotifications() {
const dispatch = useDispatch();
return (items: FormatedSubscription) => {
const formatSubscriptions = valuesIn(items);
dispatch(Events.updateNotifications(formatSubscriptions as Subscription[]));
};
}
而且我可以简单地调用它而不会出现打字稿错误询问我 "Expect 1 argument but got 0" :
const updateNotifications = Core.updateNotifications();
updateNotifications(notifications);
希望对以后的人有所帮助。