我如何使用Redux Toolkit解决'AsyncThunkAction'类型中缺少属性'type'的问题(使用TypeScript)?

问题描述 投票:0回答:1

我正在使用Redux Toolkit和下面的thunkslice。与其在状态中设置错误,我想我可以通过等待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>'

错误出现在通过 resultActionmatch:

enter image description here

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

谢谢你的帮助!

reactjs typescript redux redux-thunk redux-toolkit
1个回答
2
投票

很确定你使用的是标准内置的 Dispatch 类型,它对thunks一无所知。

根据 Redux 和 RTK 文档,你需要定义一个更具体的 AppDispatch 类型,正确了解thunks,并声明 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
    }
© www.soinside.com 2019 - 2024. All rights reserved.