【发布时间】:2020-12-16 14:03:23
【问题描述】:
我正在使用 Typescript 和 react-redux,并尝试为我的 API 请求制作自定义动态中间件。
这是我的代码:
import { Dispatch } from "react";
import { errorHandler } from "../components/Layout/SnackBar/alert";
import { API } from "../_helpers/api";
import { getTheTime } from "../_helpers/constants";
import { AppActions, AppState } from "../_types";
export const BankPages = {
posts: { name: "POSTS", api: "/post/v2" },
lessons: { name: "LESSONS", api: "/lesson/v2" },
guides: { name: "GUIDES", api: "/lesson/v2/guide" },
courses: { name: "COURSES", api: "/lesson/v2/course" },
exercises: { name: "EXERCISES", api: "/lesson/v2?course=125" },
};
export const requestBank = (page: keyof typeof BankPages) => (
dispatch: Dispatch<AppActions>,
getState: () => AppState
) => {
const bankState = getState().bank[page];
const currentTime = getTheTime();
const resetTime = currentTime - bankState.nextLoad;
if (bankState.data && resetTime <= 0) {
return;
}
dispatch({ type: `REQUEST_${BankPages[page].name}` });
API.get(BankPages[page].api)
.then((res) =>
dispatch({
type: `SUCCESS_${BankPages[page].name}`,
payload: {
data: res.data,
nextLoad: getTheTime(10),
},
})
)
.catch((err) => errorHandler(err, `FAILURE_${BankPages[page].name}`));
};
我在 type dispatch({ type: ... }) : The expected type comes from property 'type' which is declared here on type 'AppActions'
这是我的类型的样子:
export const REQUEST_POSTS = "REQUEST_POSTS";
export interface RequestPosts {
type: typeof REQUEST_POSTS;
}
一切都很完美,我知道这是因为我声明了typeof REQUEST_POSTS。
我该如何解决这个错误?
【问题讨论】:
-
typeof REQUEST_POSTS的界面对我来说看起来不错。引起我注意的是您如何为调度“构建”您的类型。type: 'SUCCESS_${BankPages[page]}'这在我看来是错误的,它可能不是一个有用的字符串。 -
@ian 感谢您的评论,您更喜欢哪种方式制作动态字符串?
-
重点不在于偏好。
BankPages[page]不是字符串而是对象。我不知道您是如何定义 AppActions 的,但它可能不会期望字符串化对象。你可能想添加.name -
感谢
you probably wanted to add .name的帮助。
标签: reactjs typescript redux middleware