簡體   English   中英

如何在鈎子函數中調用reducer動作

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM