如何使用 Redux Toolkit(使用 TypeScript)解决“AsyncThunkAction"类型中缺少“属性"类型? [英] How do I resolve 'Property 'type' is missing in type 'AsyncThunkAction' using Redux Toolkit (with TypeScript)?

查看:268
本文介绍了如何使用 Redux Toolkit(使用 TypeScript)解决“AsyncThunkAction"类型中缺少“属性"类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

const onSubmit = async (data: LoginFormData) =>{const resultAction = await dispatch(performLocalLogin(data));如果(performLocalLogin.fulfilled.match(resultAction)){unwrapResult(resultAction)} 别的 {//resultAction.payload 也不可用}};

惊呼:

export const performLocalLogin = createAsyncThunk('auth/performLocalLogin',异步 (数据:登录表单数据,{ dispatch, requestId, getState, rejectWithValue, 信号, 额外 }) =>{尝试 {const res = await api.auth.login(data);const { 令牌,记住我 } = res;dispatch(fetchUser(token, rememberMe));返回资源;} 抓住(错误){const 错误:AxiosError= 错误;如果 (!error || !error.response) {抛出错误;}返回rejectWithValue(error.response.data);}});

切片:

const authSlice = createSlice({名称:'auth',初始状态,减速器:{/* ... */},extraReducers: builder =>{builder.addCase(performLocalLogin.pending, (state, action) => startLoading(state));builder.addCase(performLocalLogin.rejected, (state, action) => {//...});builder.addCase(performLocalLogin.fulfilled, (state, action) => {如果(动作.有效载荷){state.rememberMe = action.payload.rememberMe;state.token = action.payload.token;}});}})

感谢您的帮助!

解决方案

很确定您正在使用标准的内置 Dispatch 类型,它对 thunk 一无所知.

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

//store.ts导出类型 AppDispatch = typeof store.dispatch;//我的组件.tsconst 调度:AppDispatch = useDispatch();const onSubmit = async() =>{//现在 dispatch 应该识别 thunk 实际返回的内容}

I'm using Redux Toolkit with the thunk/slice below. Rather than set the errors in state, I figure I could just handle them locally by waiting for the thunk promise to resolve, using the example provided here.

I guess I could avoid doing this, and perhaps I should, by setting an error in the state but I sort of want to understand where I went wrong on this.

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

The error arises when passing 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;
      }
    });
  }
})

Thank you for any help!

解决方案

Pretty sure that you're using the standard built-in Dispatch type there, which doesn't know anything about thunks.

Per the Redux and RTK docs, you'll need to define a more specific AppDispatch type that correctly knows about thunks and declare that dispatch here is that type, like:

    // 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
    }

这篇关于如何使用 Redux Toolkit(使用 TypeScript)解决“AsyncThunkAction"类型中缺少“属性"类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆