将AsyncThunkAction传递给unwrapResult

如何解决将AsyncThunkAction传递给unwrapResult

我正在关注Redux Essentials教程,并且在第5部分Async Logic and Data Fetching中遇到了问题。尽管本教程中未使用TypeScript,但我仍在使用TypeScript,因为我想同时学习Redux和TypeScript。

Checking Thunk Results in Components部分中,调用Redux的unwrapResult函数时遇到无法识别的类型错误。

这是错误:

TypeScript error in redux-essentials-example-app/src/features/posts/AddPostForm.tsx(34,22):
Argument of type 'AsyncThunkAction<Post,InitialPost,{}>' is not assignable to parameter of type 'ActionTypesWithOptionalErrorAction'.
  Property 'payload' is missing in type 'AsyncThunkAction<Post,{}>' but required in type '{ error?: undefined; payload: any; }'.  TS2345

    32 |         setAddRequestStatus("pending");
    33 |         const result = await dispatch(addNewPost({ title,content,user: userId }));
  > 34 |         unwrapResult(result);
       |                      ^
    35 |         setTitle("");
    36 |         setContent("");
    37 |         setUserId("");

这是我键入的AddPostForm.tsx版本的完整内容:

import React,{ useState } from "react";
import { useDispatch,useSelector } from "react-redux";
import { unwrapResult } from "@reduxjs/toolkit";

import { RootState } from "../../app/store";
import { addNewPost } from "./postsSlice";

export default function AddPostForm() {
  const [title,setTitle] = useState("");
  const [content,setContent] = useState("");
  const [userId,setUserId] = useState("");
  const [addRequestStatus,setAddRequestStatus] = useState("idle");

  const dispatch = useDispatch();
  const users = useSelector((state: RootState) => state.users);

  const onTitleChanged = (e: React.ChangeEvent<HTMLInputElement>) => {
    setTitle(e.target.value);
  };
  const onContentChanged = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setContent(e.target.value);
  };
  const onAuthorChanged = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setUserId(e.target.value);
  };

  const canSave = [title,userId].every(Boolean) && addRequestStatus === "idle";

  const onSavePostClicked = async () => {
    if (canSave) {
      try {
        setAddRequestStatus("pending");
        const result = await dispatch(addNewPost({ title,user: userId }));
        unwrapResult(result);
        setTitle("");
        setContent("");
        setUserId("");
      } catch (err) {
        console.error("Failed to save the post: ",err);
      } finally {
        setAddRequestStatus("idle");
      }
    }
  };

  const usersOptions = users.map(user => (
    <option key={user.id} value={user.id}>
      {user.name}
    </option>
  ));

  return (
    <section>
      <h2>Add a new post</h2>
      <form>
        <label htmlFor="postTitle">Post Title:</label>
        <input type="text" id="postTitle" name="postTitle" value={title} onChange={onTitleChanged} />
        <label htmlFor="postAuthor">Author:</label>
        <select id="postAuthor" value={userId} onChange={onAuthorChanged}>
          <option value=""></option>
          {usersOptions}
        </select>
        <label htmlFor="postContent">Content:</label>
        <textarea id="postContent" name="postContent" value={content} onChange={onContentChanged} />
        <button type="button" onClick={onSavePostClicked} disabled={!canSave}>Save post</button>
      </form>
    </section>
  );
}

这是我键入的redux-essentials-example-app / src / features / posts / postsSlice.tsx的完整内容:

import { createAsyncThunk,createSlice } from "@reduxjs/toolkit";

import { RootState } from "../../app/store";
import { client } from "../../api/client";

export interface PostState {
  posts: Post[],status: "idle" | "loading" | "succeeded" | "failed",error: string | null,}

export interface Post {
  id: string,date: string,title: string,content: string,user: string,reactions: Reactions,}

export interface Reactions {
  thumbsUp: number,hooray: number,heart: number,rocket: number,eyes: number,[key: string]: number,}

const initialState: PostState = {
  posts: [],status: "idle",error: null,};

export const fetchPosts = createAsyncThunk("posts/fetchPosts",async () => {
  const response = await client.get("/fakeApi/posts");
  return response.posts;
});

interface InitialPost {
  title: string,}

export const addNewPost = createAsyncThunk<Post,InitialPost>(
  "posts/addNewPost",async (initialPost) => {
    const response = await client.post("/fakeApi/posts",{ post: initialPost });
    return response.post;
  }
);

const postsSlice = createSlice({
  name: "posts",initialState,reducers: {
    postUpdated: (state,action) => {
      const { id,title,content } = action.payload;
      const existingPost = state.posts.find(post => post.id === id);

      if (existingPost) {
        existingPost.title = title;
        existingPost.content = content;
      }
    },reactionAdded: (state,action) => {
      const { postId,reaction } = action.payload;
      const existingPost = state.posts.find((post: Post) => post.id === postId);
      if (existingPost) {
        existingPost.reactions[reaction]++;
      }
    },},extraReducers: builder => {
    builder.addCase(fetchPosts.pending,(state) => {
      state.status = "loading";
    });
    builder.addCase(fetchPosts.fulfilled,(state,action) => {
      state.status = "succeeded";
      state.posts = state.posts.concat(action.payload);
    });
    builder.addCase(fetchPosts.rejected,action) => {
      state.status = "failed";
      if (action.error.message) {
        state.error = action.error.message;
      }
    });
    builder.addCase(addNewPost.fulfilled,action) => {
      state.posts.push(action.payload);
    });
  },});

export const { postUpdated,reactionAdded } = postsSlice.actions;

export function selectAllPosts(state: RootState) {
  return state.posts.posts;
}

export function selectPostById(state: RootState,postId: string) {
  return state.posts.posts.find((post: Post) => post.id === postId);
}

export default postsSlice.reducer;

我查看了Redux Toolkit的源代码,并且未导出ActionTypesWithOptionalErrorAction类型,因此似乎传递给unwrapResult的对象必须是某种形状,而不是声明为某种形状。类型。类型错误表示缺少payload属性,但是如果我注释掉unwrapResult调用并改为使用console.log(result)检查对象,则肯定存在该属性。因此,这似乎是使类型正确的问题,而不是代码中的逻辑错误。如何正确输入?

解决方法

我知道了。从react-redux调用useDispatch时,必须指定“ dispatch”类型。这在Usage With TypeScript: Getting the Dispatch Type中有描述。

最后,我将以下这些额外类型添加到了创建Redux存储的文件中:

export type AppDispatch = typeof store.dispatch;

export function useAppDispatch() {
  return useDispatch<AppDispatch>();
}

然后在src / features / posts / AddPostForm.tsx中,我导入了useAppDispatch而不是useDispatch,并使用了它。

,

我在尝试解决相同问题时碰到了这一点。我没有创建一个useAppDispatch()函数来修饰类型,而是意识到我在configureMiddleware商店中没有将thunk类型作为调度动作。

this page上,他们说使用对中间件定义的回调将包括正确的键入。我一直在使用的地方:

const store = configureStore({
  reducer: rootReducer,middleware: […getDefaultMiddleware(),logger]
})

将其更改为

const store = configureStore({
  reducer: rootReducer,middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger)
})

实际上已解决了该问题,因为store.dispatch()现在将AsyncThunkAction包括在可接受的参数类型列表中。这是一个更好的解决方案,但我希望它包含在有关configureStore的redux工具包文档中。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-