带有Typescript的Redux工具包.无法调度createAsyncThunk创建的操作



我正在使用ReactRedux Toolkit实现登录功能。然而,当试图调度createAsyncThunk函数创建的操作时,我得到了错误:

类型为"AsyncThunkAction<"的参数;用户,UserCredentials,{}>'不是可分配给"AnyAction"类型的参数。属性"type"为类型"AsyncThunkAction<"中缺少;用户,UserCredentials,{}>'但是类型"AnyAction"中需要。ts(2345(

我在谷歌上搜索了可能的解决方案,但找不到任何适合我的解决方案。以下是我的实现,它是根据官方ReduxToolkit文档完成的。

用户切片.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;

存储.ts:

export const store = configureStore({
reducer: {
user: userReducer,
}
});
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

钩子.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中。我会查一下的。

值得一提的是,我走上了redux版本、yarn-flat、包升级等的道路。

我的useAppDispatch输入正确,我不确定它还能是什么。

虽然上面的评论可能已经解决了这个问题,但我的评论是由以下愚蠢的错误解决的:

导入操作必须放在大括号中,如下所示:

import { action } from '../path/to/slice';

我没有正确导入操作,它反而获取了我的reducer对象。希望这能帮助任何有同样经历的人!

最新更新