React Redux Toolkit 不调度 Async Thunk



我正在使用Redux/Toolkit,我想使用Async Thunk进行身份验证过程。但是,当我试图调度函数时,它返回一个错误。

在这种情况下我该怎么做?这是我第一次使用Async Thunk,所以我不知道如何面对这个问题。

顺便说一下,我使用的是Typescript。所以,我认为这个问题主要是关于Typescript的。

userSlice。tsx文件:

import {createSlice, createAsyncThunk} from "@reduxjs/toolkit"
import {InterfaceUserSlice} from "../typescript/interfaceUserSlice"
import axios from "../axios"
export const UserLogin = createAsyncThunk("/users/authentication", async (user:{email:string,password:string}) => {
try{
const res = await axios.post("/users/authentication", user)
...
} catch(err){
...
}
})
const initialState:InterfaceUserSlice = {
...
}
const userSlice = createSlice({
name: "user",
initialState,
reducers: {},
extraReducers: (builder) => {}
})
export default userSlice.reducer

登录。TSX页面文件:

import React, {useState} from "react"
import { useDispatch } from "react-redux"
import { UserLogin } from "../redux/userSlice"
const Login = () => {
const dispatch = useDispatch()
const [email, setEmail] = useState<string>("")
const [password, setPassword] = useState<string>("")

function LoginRequest(){
dispatch(UserLogin({email,password})) //This is the point that I have the error which says: "Argument of type 'AsyncThunkAction<void, { email: string; password: string; }, AsyncThunkConfig>' is not assignable to parameter of type 'AnyAction'."
}

return (
...
)
}
export default Login

如果你使用TypeScript,你总是应该在泛型中设置asyncThunk的返回类型和参数

export const UserLogin = createAsyncThunk<return type, arguments>("/users/authentication", async (user) => {
try{
const res = await axios.post("/users/authentication", user)
...
} catch(err){
...
}
})

你还应该创建自定义钩子useDispatch和useSelector


import { useSelector, useDispatch, TypedUseSelectorHook } from "react-redux";
import type { RootState, AppDispatch } from "../redux/store";
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;


主减速器文件应该是这样的:

import { configureStore } from "@reduxjs/toolkit";
import userleSlice from "./slice/userSlice";
export const store = configureStore({
reducer: {
user: userSlice,
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

尝试将参数的类型传递给createAsyncThunk:

type ReturnedType = any // The type of the return of the thunk
type ThunkArg = { email:string, password:string } 
export const UserLogin = createAsyncThunk<ReturnedType, ThunkArg>("/users/authentication", async (user) => {
try{
const res = await axios.post("/users/authentication", user)
...
} catch(err){
...
}
})

最新更新