1

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

[ts] '(dispatch: Dispatch) => void' 类型的参数不可分配给'PostActionTypes' 类型的参数。类型“(dispatch:Dispatch)=> void”缺少类型“GetDetailsFailAction”的以下属性:类型,有效负载[2345](别名)initPosts():(dispatch:Dispatch)=> void import initPosts

在另一个 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));
      });
  };
};
4

1 回答 1

0

如此处所述

您应该将其键入为,

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));
      });
  };
};

于 2020-11-18T09:34:25.490 回答