簡體   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