【问题标题】:React - could not send a redux-thunk action with extra argumentReact - 无法发送带有额外参数的 redux-thunk 动作
【发布时间】:2020-02-19 13:05:59
【问题描述】:

我尝试使用带有 redux-thunk 和 redux 的 typescript。 我想将一个对象传递给任何操作(我正在使用依赖注入,我需要传递一个对象服务或字符串)

我收到了这个错误;

  Overload 1 of 2, '(action: AnyAction): AnyAction', gave the following error.
    Argument of type '(dispatch: any, getState: AppState, extraArg: string) => Promise<any>' is not assignable to parameter of type 'AnyAction'.

如下:

store.ts:

const middlewares = [
    routerMiddleware(history),
    thunkMiddleware.withExtraArgument('bar') as ThunkMiddleware<
      AppState,
      Actions,
      string
    >
  ];
  const middleWareEnhancer = applyMiddleware(...middlewares);

  const store = createStore(
    rootReducer(history),
    preloadState,
    composeWithDevTools(middleWareEnhancer)
  );

我试图发送操作的 index.ts 是:

(store.dispatch as ThunkDispatch<{}, void, AnyAction>)(getAll());

我的动作文件有效:

export const getall = () => async (dispatch: any) => {
  try {
    dispatch({ type: GETALL_REQUEST });
    return dispatch({ type: GETALL_SUCCESS, payload: null });
  } catch (e) {
    return dispatch({ type: GETALL_FAILURE, error: e });
  }
};

引发错误的我的操作(放入其中的一部分)

export const getAll = () => async (
  dispatch: any,
  getState: AppState,
  extraArg: string
) => {....action logic}

然后我得到了错误:

(store.dispatch as ThunkDispatch<{}, void, AnyAction>)(getAll());

【问题讨论】:

    标签: reactjs typescript redux redux-thunk


    【解决方案1】:

    纠正错误的最简单方法:

    (store.dispatch as ThunkDispatch<AppState, string, AnyAction>)(getAll());
    

    export const getAll = () => async (
      dispatch: any,
      getState: () => AppState,
      extraArg: string
    ) => {....action logic}
    
    1. ThunkDispatch 接受以下类型参数:S - 状态,E - 扩展参数,A - 操作。因此,您对ThunkDispatch 的使用应该与您的状态类型和扩展参数相匹配。

    2. Thunk 动作是一个接受以下参数的函数:dispatch 是一个函数,getState 也是一个返回状态的函数,extraArg。所以请确保 getState 是一个函数。

    为避免dispatch 强制转换,我建议在创建时正确键入商店。当您使用接受数组的applyMiddleware 时,您应该将类​​型参数传递给它。它接受将在申请特拉华州后使用的调度类型。

    const middlewares = [thunk.withExtraArgument("bar")];
    const middleWareEnhancer = applyMiddleware<
      ThunkDispatch<AppState, string, Actions>
    >(...middlewares);
    

    因此,您将获得一个具有正确键入的调度功能的商店。而且您无需强制转换即可使用它。

    store.dispatch(getAll());
    

    工作的demo

    【讨论】:

      猜你喜欢
      • 2020-05-25
      • 2019-01-08
      • 2022-12-21
      • 2021-07-21
      • 2021-10-03
      • 2019-02-02
      • 2019-11-14
      • 2018-05-21
      • 1970-01-01
      相关资源
      最近更新 更多