繁体   English   中英

React Redux Toolkit 不发送 Async Thunk

[英]React Redux Toolkit Doesn't Dispatch 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

Login.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

尝试将 args 的类型传递给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){
    ...
  }
})

如果你使用 TypeScript,你总是应该在 genric 中为你的 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM