[英]how to call the reducer action inside hook function
我有一个减速器,包括两个动作,一个是设置一些状态shouldUpdateTime
至真/假和其他动作的状态恢复到初始化状态为假,我想打电话给行动resetShouldUpdateTime
下钩useUpdateTime
引起了一些API请求后
我想我不能改变钩子函数内的状态,但我该怎么做?
//clockReducers
interface ReducerValue {
shouldUpdateTime: boolean;
}
export const initialState: ReducerValue = {
shouldUpdateTime: false,
};
export const clockSlice = createSlice({
name: 'clock',
initialState,
reducers: {
setShouldUpdateTime: (state: ReducerValue, action: PayloadAction<boolean>) => {
return {...state, shouldUpdateTime: action.payload};
},
resetShouldUpdateTime: (state: ReducerValue) => {
return {...state, shouldUpdateTime: false};
},
},
});
export const {
setShouldUpdateTime
} = clockSlice.actions;
export const clockReducer = clockSlice.reducer;
// middleware for updateTime
const updateTimeMiddleware = (action: AnyAction): AppThunk => {
return async (dispatch, getState) => {
const prevTime = getState()?.unitTime || {};
dispatch(action)
const newTime = getState()?.unitTime || {};
dispatch(setShouldUpdateTime(prevTime > newTime));
};
};
// hook
function useUpdateTime(){
const shouldUpdateTime = useSelector(
(state: AppState) => state.clockReducer.shouldUpdateTime
);
... do some api request
// I would like to call resetShouldUpdateTime action to set shouldUpdateTime state to false
}
export default function App() {
const onClickHandler = useCallBack(() =>{
useDispatch(updateTimeMiddleware(someAction))
})
return (
<div className="App">
<button onClick={onClickHandler}>Hello CodeSandbox</button>
</div>
);
}
在您的自定义钩子中,您可以使用useDispatch获取对 Redux 商店的 dispatch 函数的引用。
从createSlice返回的对象看起来像
{
name : string,
reducer : ReducerFunction,
actions : Record<string, ActionCreator>,
caseReducers: Record<string, CaseReducer>
}
reducers 参数中定义的每个函数都将有一个使用 createAction 生成的相应动作创建者,并使用相同的函数名称包含在结果的动作字段中。
所以你可以像这样使用 store 的 dispatch 函数和resetShouldUpdateTime
操作:
function useUpdateTime() {
const dispatch = useDispatch();
//... do some api request
// I would like to call resetShouldUpdateTime action to set shouldUpdateTime state to false
dispatch(clockSlice.actions.resetShouldUpdateTime());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.