1

根据 Redux 的 typescript 定义,应该实现这些接口来制作 middelware:

/* 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' 

更新:

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

4

2 回答 2

3

你可以看看我的代码。应该是这样的:

  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
        })
      );
  };
于 2019-04-11T19:16:18.323 回答
0

首先没有“redux 中间件类”这样的东西。因此,您的操作方法问题的答案很简单,您不能。

ReduxMiddleware是一个函数接口,而不是类接口。尽管在javascript中您可以强制从类构造函数返回一个函数(而不是this对象),但您不应该使用typescript。编译器可能会抱怨它是一种反模式,并且类语法不适用于这种 hacky 用法。即使它没有抱怨,我认为这种黑客攻击绝对是零收益。

所以你想实现一些“可继承”的东西。您不必使用类语法。具有讽刺意味的是,您可以使用中间件模式。在子中间件给你继承效果之前应用基础中间件。

现在我不知道你打算做什么,所以不会编造毫无意义的例子。如果您愿意解释您要做什么,我会调查一下。

于 2019-04-14T07:59:28.833 回答