如何使用 Redux Toolkit(使用 TypeScript)解决“AsyncThunkAction”类型中缺少“属性”类型?

Cha*_*nce 10 typescript reactjs redux redux-thunk redux-toolkit

我将 Redux Toolkit 与下面的 thunk/slice 一起使用。与其在 state 中设置错误,我想我可以通过等待 thunk 承诺解决来在本地处理它们,使用这里提供的示例

我想我可以避免这样做,也许我应该通过error在 state 中设置 an 来避免这样做,但我有点想了解我在这方面出了什么问题。

Argument of type 'AsyncThunkAction<LoginResponse, LoginFormData, {}>' is not assignable to parameter of type 'Action<unknown>'.
  Property 'type' is missing in type 'AsyncThunkAction<LoginResponse, LoginFormData, {}>' but required in type 'Action<unknown>'
Run Code Online (Sandbox Code Playgroud)

传递resultAction到时出现错误match

在此处输入图片说明

const onSubmit = async (data: LoginFormData) => {
  const resultAction =  await dispatch(performLocalLogin(data));
  if (performLocalLogin.fulfilled.match(resultAction)) {
    unwrapResult(resultAction)
  } else {
    // resultAction.payload is not available either
  }
};
Run Code Online (Sandbox Code Playgroud)

猛击:

export const performLocalLogin = createAsyncThunk(
  'auth/performLocalLogin',
  async (
    data: LoginFormData,
    { dispatch, requestId, getState, rejectWithValue, signal, extra }
  ) => {
    try {
      const res = await api.auth.login(data);
      const { token, rememberMe } = res;
      dispatch(fetchUser(token, rememberMe));
      return res;
    } catch (err) {
      const error: AxiosError<ApiErrorResponse> = err;
      if (!error || !error.response) {
        throw err;
      }
      return rejectWithValue(error.response.data);
    }
  }
);
Run Code Online (Sandbox Code Playgroud)

片:

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: { /* ... */ },
  extraReducers: builder => {
    builder.addCase(performLocalLogin.pending, (state, action) => startLoading(state));
    builder.addCase(performLocalLogin.rejected, (state, action) => {
      //...
    });
    builder.addCase(performLocalLogin.fulfilled, (state, action) => {
      if (action.payload) {
        state.rememberMe = action.payload.rememberMe;
        state.token = action.payload.token;
      }
    });
  }
})
Run Code Online (Sandbox Code Playgroud)

感谢您的任何帮助!

mar*_*son 19

很确定你在Dispatch那里使用标准的内置类型,它对 thunk 一无所知。

根据 Redux 和 RTK 文档,您需要定义一个更具体的AppDispatch类型来正确了解 thunk 并声明这dispatch是该类型,例如:

    // store.ts
    export type AppDispatch = typeof store.dispatch;

    // MyComponent.ts
    const dispatch : AppDispatch = useDispatch();

    const onSubmit = async () => {
        // now dispatch should recognize what the thunk actually returns
    }
Run Code Online (Sandbox Code Playgroud)

  • 在将“dispatch”声明为“AppDispatch”后,我仍然看到类型错误,因为我使用扩展运算符来定义商店的“中间件”选项。如文档所述,使用 getDefaultMiddleware().concat(...) 来修复它。 (7认同)
  • 这是一个经常被引用的问题,因此我们显然需要更新文档以进一步强调它。 (2认同)