gpt4 book ai didi

javascript - 如何在 TypeScript 中实现 redux 中间件类

转载 作者:行者123 更新时间:2023-11-30 11:06:07 25 4
gpt4 key购买 nike

根据 Redux 的 typescript 定义,应该实现这些接口(interface)来制作中间件:

/* middleware */

export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> {
dispatch: D
getState(): S
}

/**
* A middleware is a higher-order function that composes a dispatch function
* to return a new dispatch function. It often turns async actions into
* actions.
*
* Middleware is composable using function composition. It is useful for
* logging actions, performing side effects like routing, or turning an
* asynchronous API call into a series of synchronous actions.
*
* @template DispatchExt Extra Dispatch signature added by this middleware.
* @template S The type of the state supported by this middleware.
* @template D The type of Dispatch of the store where this middleware is
* installed.
*/
export interface Middleware<
DispatchExt = {},
S = any,
D extends Dispatch = Dispatch
> {
(api: MiddlewareAPI<D, S>): (
next: Dispatch<AnyAction>
) => (action: any) => any
}

我试过这个:

import { Middleware, Dispatch, AnyAction, MiddlewareAPI } from 'redux';
import { AppState } from 'AppState';

class MiddlewareBase implements Middleware<{}, AppState, Dispatch<AnyAction>> {
constructor() {
return (api: MiddlewareAPI<Dispatch<AnyAction>, AppState>) =>
(next: Dispatch<AnyAction>) =>
(action: AnyAction) =>
{
// TODO: Do something before calling the next middleware.
return next(action);
};
}
}

export default MiddlewareBase;

但是编译器对此有提示:

  Type 'MiddlewareBase' provides no match for the signature '(api: MiddlewareAPI<Dispatch<AnyAction>, AppState>): (next: Dispatch<AnyAction>) => (action: any) => any' 

更新:

它应该是一个类,而不是一个函数。我创建了一个基类,以便以后可以继承它们。

最佳答案

可以看看my code .应该是这样的:

  import { MiddlewareAPI, Dispatch, Middleware, AnyAction } from "redux";

const callAPIMiddleware: Middleware<Dispatch> = ({
dispatch
}: MiddlewareAPI) => next => (action: AnyAction | CallApiAction) => {
if (!action.meta || !action.meta.callApi) {
return next(action);
}

const { successAction, errorAction, url, params } = action.payload;

return fetchFn(url, params)
.then(res => res.json())
.then(res =>
dispatch({
type: successAction,
payload: res
})
)
.catch(res =>
dispatch({
type: errorAction,
payload: res
})
);
};

关于javascript - 如何在 TypeScript 中实现 redux 中间件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55553874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com