如何在打字稿中访问 redux 工具包中的 getState?

How to access getState in redux toolkit in typescript?

我有一个 createAsyncThunk 操作,想访问工具包中的 getState。我不确定如何在打字稿中输入 getState 类型:

export const getInitialDatapoints = createAsyncThunk(
  'userSlice/getInitDatapoints',
  async (args, { getState as AppState }) => {
    const geoData = await getLocationData();
    const googleData = getState().userSlice;
    const response = await updateUserData(1);
    return response.data;
  }
);

其中 AppStore 是:

export type AppState = ReturnType<typeof store.getState>;

我收到这个错误:

Property 'AppState' does not exist on type 'GetThunkAPI<{}>'

谁能帮忙解决这个问题?

您不能在解构对象时进行类型转换。此外,您需要先调用 getState 才能将其转换为 AppState.

您可以这样做:

const getInitialDatapoints = createAsyncThunk(
        "userSlice/getInitDatapoints",
        // you could also just stick to { getState }; call and
        // cast it in the line below.
        async (args, api) => {
            const appState = api.getState() as AppState
            const geoData = await getLocationData();
            const googleData = appState.userSlice;
            const response = await updateUserData(1);
            return response.data;
        }
    );