如何在钩子函数中调用 reducer 动作

how to call the reducer action inside hook function

我有一个包含两个动作的减速器,一个是将一些状态设置为 shouldUpdateTime 到 true/false,另一个动作是将状态重置为 initialState 为 false 我想在一些 api 请求触发

后调用挂钩 useUpdateTime 下的操作 resetShouldUpdateTime

我想我不能改变钩子函数内的状态,但我该怎么做呢?

//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 存储的调度函数的引用。

createSlice返回的对象看起来像

{
    name : string,
    reducer : ReducerFunction,
    actions : Record<string, ActionCreator>,
    caseReducers: Record<string, CaseReducer>
}

Each function defined in the reducers argument will have a corresponding action creator generated using createAction and included in the result's actions field using the same function name.

因此您可以像这样将商店的调度功能与 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());
}