我们可以使用自定义 Hooks 和 redux Saga 函数吗

Can we use customHooks into redux Saga function

跟随自定义挂钩作为状态选择器并在“功能视图”组件中使用它。 现在,我需要在 redux Saga 函数中使用它。我们可以在 Saga 函数中使用它吗,或者我必须使用其他方法而不是在 Saga 函数中使用自定义挂钩?

export function useSelectAllEntries()
{
return useSelector(
({allEntries=[]}) =>[...allEntries],shallowEqual
);
}

export function useSelectFilteredByMakeEntries()
{
const selectAll = useSelectAllEntries();
return selectAll.filter(...);
}

export function useSelectFilteredByCreatorEntries()
{
const selectAll = useSelectAllEntries();
return selectAll.filter(...);
}

与其将它们定义为自定义挂钩,不如将它们定义为选择器。 Redux 选择器可以在多个不同的用例之间自由共享。

export const allEntriesSelector = ({ allEntries = [] }) => allEntries;

export const allEntriesFilteredByMakeEntriesSelector = state =>
  allEntriesSelector(state).filter(...);

export const allEntriesFilteredByCreatorEntriesSelector = state =>
  allEntriesSelector(state).filter(...);

然后,当你想在功能组件中使用它们时,只需调用 useSelector:

function MyComponent() {
  const entries = useSelector(allEntriesSelector);
  const filteredByMake = useSelector(allEntriesFilteredByMakeEntriesSelector);
  const filteredByCreator = useSelector(allEntriesFilteredByCreatorEntriesSelector);

  return (...);
}

以及当您想在 saga 中使用它们时:

import { select } from 'redux-saga/effects';

function* mySaga() {
  const entries = yield select(allEntriesSelector);
  const filteredByMake = yield select(allEntriesFilteredByMakeEntriesSelector);
  const filteredByCreator = yield select(allEntriesFilteredByCreatorEntriesSelector);
}