Redux-toolkit 中异步操作的打字稿等价物是什么

What is the typescript equivalent for Asynchronous action in Redux-toolkit

我正在尝试将打字稿添加到 redux 工具包应用程序中。这是一个简单的计数器应用程序,用于将计数器状态增加或减少一个。

import {
  createSlice,
  Dispatch,
  PayloadAction
} from "@reduxjs/toolkit";

export interface CounterState {
  value: number;
};

const initialState: CounterState = {
  value: 0
};

export const counterSlice = createSlice({
  name: 'Counter Slice',
  initialState: initialState,
  reducers: {
    increment: (state) => {
      state.value = state.value + 1;
    },
    decrement: (state) => {
      state.value = state.value - 1;
    },
    incrementByAmount: (state, action: PayloadAction < number > ) => {
      state.value = state.value + action.payload;
    }
  }
});

//What would be the type of "incrementAsync"
export const incrementAsync: any = (amount: number) => (dispatch: Dispatch) => {
  setTimeout(() => {
    dispatch(incrementByAmount(amount));
  }, 1000);
};

export const {
  increment,
  decrement,
  incrementByAmount
} = counterSlice.actions;
export default counterSlice.reducer;

incrementAsync 的类型注释应该是什么,而不是我用来使其工作的 any 类型。官方 redux 工具包文档对我没有帮助。

incrementAsync只是使用超时函数,延迟一秒后计数器值加一

我认为你需要使用 createAsyncThunk()。与 TypeScript 一起看起来像这样:

export const incrementAsync = createAsyncThunk<void, number>(
  "counter/incrementAsync",
  async (amount, { dispatch }) => {
    setTimeout(() => {
      dispatch(incrementByAmount(amount))
    }, 1000)
  }
)

这样你的函数 incrementAsync 是通过从函数 createAsyncThunk()

推断类型来输入的

参考 createAsyncThunk together with TypeScript

那里不需要类型注释 - TypeScript 已经很清楚

(amount: number) => (dispatch: Dispatch) => {
  setTimeout(() => {
    dispatch(incrementByAmount(amount));
  }, 1000);
};

属于

类型
(amount: number) => (dispatch: Dispatch) => void

.

你不需要写下来,也不需要别名——它已经可以很好地与 Redux 一起工作了。只需跳过 const.

上的手动类型注释

您可以使用 Type Checking Redux Thunks 中描述的 AppThunk 类型,但它并没有太多好处,而且老实说,我发现它更难处理。

或者你去,正如其他答案中已经建议的那样,使用 createAsyncThunk,但只有当你有真正需要 lifecicle 的东西时,你才应该这样做,所以之前的“待定”动作和“之后完成”或“拒绝”操作。