9

有什么方法可以从使用 redux-mock-store 创建的商店中正确调度 Thunk 吗?现在我被迫使用任何类型断言

store.dispatch<any>(getCommissions());

正如dispatch预期的那样提供简单的动作

[ts]
Argument of type '(dispatch: ThunkDispatch<IRootState, undefined, 
AnyAction>, getState: () => IRootState) => void' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type '(dispatch: ThunkDispatch<IRootState, undefined, AnyAction>, getState: () => IRootState) => void'.

代码片段getCommisions()

export function getCommissions() {
  return (dispatch: ThunkDispatch<IRootState, undefined, AnyAction>, getState: () => IRootState) => { ... }
4

3 回答 3

24

默认导出的createMockStore函数redux-mock-store接受泛型类型<S, DispatchExts>,其中S定义了 Redux 状态,并且DispatchExts是任何添加的 Redux 中间件的(或单个)附加Dispatch签名的联合。

所以设置它的方法是 import ThunkDispatchfrom redux-thunk,它接受它自己的通用参数<State, ExtraArgument, Action>并将其作为DispatchExts参数传递给createMockStore

这是一个简短的示例:

import { AnyAction } from 'redux'; // Or your own Action definition
import createMockStore from 'redux-mock-store';
import thunk, { ThunkDispatch } from 'redux-thunk';

import { ApplicationState } from '../your/definitions';

type DispatchExts = ThunkDispatch<ApplicationState, void, AnyAction>;

const middleware = [thunk];
const mockStore = createMockStore<ApplicationState, DispatchExts>(middleware);

const store = mockStore();

希望对你有帮助!

我当前的版本: redux 4.0.0 redux-thunk 2.3.0 redux-mock-store 1.5.3 typescript 2.9.2

ThunkDispatch定义https://github.com/reduxjs/redux-thunk/blob/master/index.d.ts

createMockStore定义https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/redux-mock-store/index.d.ts

于 2018-10-26T14:37:31.377 回答
7

对于configureMockStore使用,该解决方案与@nickpassarella 的答案几乎完全相同。

import configureMockStore from 'redux-mock-store';
import thunk, { ThunkDispatch } from 'redux-thunk';
import { MyState, MyActions } from './my-types';

type DispatchExts = ThunkDispatch<MyState, undefined, MyActions>;

const middlewares = [thunk];
const mockStore = configureMockStore<MyState, DispatchExts>(middlewares);

const store = mockStore();

这两个示例都使用redux 4.0.1 redux-thunk 2.3.0 redux-mock-store 1.5.3typescript 3.5.3

于 2019-09-19T05:51:34.467 回答
0

在类似的情况下,我发现了一个用 Typescript 编写的库的更新版本,并且可以更好地与最新版本的 redux ( 4.0.4) 和 redux-thunk配合使用2.3.0

https://github.com/jedmao/redux-mock-store

于 2019-11-22T23:35:18.003 回答