【问题标题】:Thunk action creators dispatch another thunk action creators, but typescript throw an error. What type should i add?Thunk 动作创建者派出另一个 thunk 动作创建者,但 typescript 抛出错误。我应该添加什么类型?
【发布时间】:2020-03-11 10:37:17
【问题描述】:

如何让打字稿不抱怨或如何解决?

[ts] '(dispatch: Dispatch) => void' 类型的参数不可分配给'PostActionTypes' 类型的参数。 类型“(调度:调度)=> void”缺少类型“GetDetailsFailAction”的以下属性:类型、有效负载 [2345] (别名) initPosts(): (dispatch: Dispatch) => void 导入初始化帖子

在另一个 thunk 动作中调度 thunk 动作时我需要添加什么类型?

import axios from "axios";
import { initPosts } from "./init";
import { Dispatch } from "redux";
import { AppActions } from "../types/actions";

export const deletePost = (id: string) => {
  return (dispatch: Dispatch<AppActions>) => {
    axios
      .delete(`https://#####/posts/${id}`)
      .then(response => {
        if (response.status === 200) {
          dispatch(initPosts()); // error here
        }
      })
      .catch(error => {
        console.log(error);
      });
  };
};

initPosts 操作

import axios from "axios";
import { AppActions } from "../types/actions";
import { IPost } from "../types/postInterface";
import { Dispatch } from "redux";

export const initPostsStart = (): AppActions => {
  return {
    type: "INIT_POSTS_START"
  };
};

export const initPostsSuccess = (allPosts: IPost[]): AppActions => {
  return {
    type: "INIT_POSTS_SUCCESS",
    payload: allPosts
  };
};

export const initPostsFail = (error: string): AppActions => {
  return {
    type: "INIT_POSTS_FAIL",
    payload: error
  };
};

export const initPosts = () => {
  return (dispatch: Dispatch<AppActions>) => {
    dispatch(initPostsStart());
    axios
      .get("https://#####/posts")
      .then(response => {
        dispatch(initPostsSuccess(response.data));
      })
      .catch(error => {
        dispatch(initPostsFail(error.message));
      });
  };
};

【问题讨论】:

    标签: reactjs typescript redux thunk


    【解决方案1】:

    据记录 here

    你应该输入它,

    import { ThunkAction as ReduxThunkAction } from 'redux-thunk';
    
    type ThunkAction = ReduxThunkAction<void, IState, unknown, Action<string>>;
    export const initPosts = (): ThunkAction => {
      return (dispatch) => {
        dispatch(initPostsStart());
        axios
          .get("https://#####/posts")
          .then(response => {
            dispatch(initPostsSuccess(response.data));
          })
          .catch(error => {
            dispatch(initPostsFail(error.message));
          });
      };
    };
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 2019-08-14
      • 2016-10-18
      • 2019-03-20
      • 2020-05-23
      • 2018-01-04
      • 2021-03-03
      相关资源
      最近更新 更多