忽略后续的 Redux Thunk 调度

Ignoring subsequent Redux Thunk dispatches

想象一下这个动作:

export const myAction = createAsyncThunk(...)

我在 2 个不同的 React 组件中分派动作,这两个组件都需要这个动作来填充它们所依赖的状态:

useEffect(() => {
  dispatch(myAction())
}, [dispatch])

这当然会导致 thunk 运行 其异步代码两次。

我想用这个 thunk 在 Redux Saga 中做一些类似于 takeLeading 的事情。

有什么方法可以让 myAction() 的后续调度在第一个 运行ning 时被忽略?

自定义钩子解决方案:

import React, { useCallback, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { myAction } from './actions';

const useMyActionNonConcurrently = () => {
    const dispatch = useDispatch();
    const isPerformingMyAction = useSelector(state => state.someSlice.isPerformingMyAction);
    const performMyAction = useCallback(
        () => {
            if (!isPerformingMyAction) {
                dispatch(myAction())
                // this thunk needs to toggle state.someSlice.isPerformingMyAction while it's running
            }
        },
        [dispatch, isPerformingMyAction]
    );
    return performMyAction;
};

// Usage in a component (on mount):
const performMyAction = useMyActionNonConcurrently();
useEffect(performMyAction, []);