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

2024-03-06

我正在使用 Redux Toolkit 和下面的 thunk/slice。我认为我可以通过等待 thunk 承诺解决来在本地处理它们,而不是在状态中设置错误,使用此处提供的示例 https://redux-toolkit.js.org/api/createAsyncThunk#examples.

我想我可以避免这样做,也许我应该通过设置一个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 to 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
  }
};

thunk:

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

slice:

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

感谢您的任何帮助!


很确定您正在使用标准内置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
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Redux Toolkit(使用 TypeScript)解决类型“AsyncThunkAction”中缺少属性“类型”的问题? 的相关文章

随机推荐