想象一下这个动作:
export const myAction = createAsyncThunk(...)
我在2个不同的React组件中分配这个动作,这两个组件都需要这个动作来填充它们所依赖的状态:
useEffect(() => {
dispatch(myAction())
}, [dispatch])
这当然会导致thunk运行两次async代码。
我想用这个想法做一些类似于《Redux Saga》中的takeLeading
的事情。
是否有一种方法可以让myAction()
的后续调度在第一个调度运行时被忽略?
自定义钩子解决方案:
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, []);