12

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

我想我可以避免这样做,也许我应该通过error在状态中设置一个,但我有点想了解我在哪里出错了。

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>'

传递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
  }
};

重击:

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);
    }
  }
);

片:

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;
      }
    });
  }
})

感谢您的任何帮助!

4

2 回答 2

22

很确定你在那里使用标准的内置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
    }
于 2020-06-06T21:57:05.600 回答
3

我必须添加middleware: [thunk as ThunkMiddleware]到我的 configureStore() 以获得 createAsyncThunk() 的正确类型

于 2021-08-29T13:43:32.550 回答