有没有办法从使用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) => { ... }发布于 2018-10-26 22:37:31
createMockStore函数是redux-mock-store的默认导出,它接受泛型类型<S, DispatchExts>,其中S是Redux状态的定义,DispatchExts是任何添加的Redux中间件的附加Dispatch签名的联合(或单个)。
因此,设置的方法是从redux-thunk导入ThunkDispatch,它接受自己的<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
发布于 2019-09-19 13:51:34
对于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.3和typescript 3.5.3
发布于 2019-11-23 07:35:18
在类似的情况下,我发现了一个用Typescript编写的更新的库分支,并且在最新版本的redux (4.0.4)和redux-thunk 2.3.0上工作得更好。
https://stackoverflow.com/questions/52648553
复制相似问题