有什么方法可以从使用 redux-mock-store 创建的商店中正确发送 Thunk 吗?现在我被迫使用任何类型断言
store.dispatch<any>(getCommissions());
因为 dispatch
期望提供简单的 Action
[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) => { ... }
最佳答案
createMockStore
redux-mock-store
的默认导出函数接受通用类型 <S, DispatchExts>
其中 S
是你的 Redux 状态的定义,DispatchExts
是(或单个)附加 Dispatch
的并集任何添加的 Redux 中间件的签名。
所以设置它的方法是导入ThunkDispatch
来自 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
关于 typescript ,单元测试 : Correct typing for Dispatching a Thunk with store. 从 redux-mock-store 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52648553/