reactjs - 带有 Typescript 的 Redux-Toolkit。无法调度由 createAsyncThunk 创建的操作

标签 reactjs typescript redux react-redux redux-toolkit

我正在使用 实现登录功能 react Redux-工具包 .但是,当尝试调度由 createAsyncThunk 创建的操作时函数我收到错误:

Argument of type 'AsyncThunkAction<User, UserCredentials, {}>' is not assignable to parameter of type 'AnyAction'. Property 'type' is missing in type 'AsyncThunkAction<User, UserCredentials, {}>' but required in type 'AnyAction'.ts(2345)


我在谷歌上搜索了可能的解决方案,但找不到任何适合我的情况。
这是我根据官方完成的实现Redux-工具包文档。
用户切片.ts:
    export interface User {
      UserId: string;
      Name: string;
      Token: string;
    }
    
    export interface UserCredentials {
      username: string;
      password: string;
    }
    
    interface AuthState {
      currentUser: User | null;
      loading: boolean;
      error: string | null;
    }
    
    const initialState: AuthState = {
      currentUser: null,
      loading: false,
      error: null
    };
    
    export const userLogin = createAsyncThunk<User, UserCredentials>(
      'users/login',
      async (credentials: UserCredentials) => {
        const response = await fetch(`${apiRest()}login`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(credentials)
        });
        console.log(await response.json());
        return (await response.json()) as User;
      }
    );
    
    export const userSlice = createSlice({
      name: 'users',
      initialState,
      reducers: { },
      extraReducers: (builder) => {
        builder
          .addCase(userLogin.pending, state => {
            state.currentUser = null;
            state.loading = true;
            state.error = null;
          })
          .addCase(userLogin.fulfilled, (state, action) => {
            state.loading = false;
            state.currentUser = action.payload;
            state.error = null;
          })
          .addCase(userLogin.rejected, (state, action) => {
            state.currentUser = null;
            state.loading = false;
            if(action.payload) {
              state.error = action.payload as string;
            } else {
              state.error = 'Failed user to login';
            }
          });
      }
    });
    
    export default userSlice.reducer;
store.ts:
export const store = configureStore({
  reducer: {
    user: userReducer,
  }
});

export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
hooks.ts:
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
登录页面.tsx:
export const LoginPage: React.FC = () => {
  const dispatch = useAppDispatch();

  const onLoginSubmit =
  useCallback(
    (login, password) =>   
      // Getting the following error here:   
      // Argument of type 'AsyncThunkAction<User, UserCredentials, {}>' is not assignable to parameter of type 'AnyAction'.
      // Property 'type' is missing in type 'AsyncThunkAction<User, UserCredentials, {}>' but required in type 'AnyAction'.
      dispatch(userLogin({username: login, password})),
    [dispatch]
  );

  const loginErrorText = useSelector(loginError);

  return (
    <div>
      <LoginForm
        onSubmit={onLoginSubmit}
        loginError={loginErrorText}
      />
    </div>
  );
};
在此先感谢您的帮助!

最佳答案

由于您的设置似乎是正确的,我假设您有一个罕见的错误,即 redux 4.0.5 和 redux 4.1.0 并排安装在您的 node_modules 中。我会检查一下。

关于reactjs - 带有 Typescript 的 Redux-Toolkit。无法调度由 createAsyncThunk 创建的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68002829/

相关文章:

django - 被 CORS 策略阻止 : No 'Access-Control-Allow-Origin' header is present on the requested resource

angular - 为什么 Angular 不在我的 ControlValueAccessor 实现中调用 registerOnChange?

angular - 如何在 Angular 2 组件中按顺序访问不同类型的子组件?

javascript - 使用 componentWillRecieveProps 调用类组件的 api

javascript - 使用 localStorage 数据更新 reducer 初始状态是一个好习惯吗?

javascript - render() 内外的函数

javascript - 在 react DRY 中稍微适应 HOC

reactjs - React useEffect 无限循环获取数据 axios

promise.reject 的 TypeScript 类型定义

reactjs - 配置react webpack进行部署