gpt4 book ai didi

typescript - 如何分派(dispatch)一个 Action 或一个 ThunkAction(在 TypeScript 中,使用 redux-thunk)?

转载 作者:搜寻专家 更新时间:2023-10-30 20:34:25 25 4
gpt4 key购买 nike

假设我有这样的代码:

import { Action, Dispatch } from 'redux';
import { ThunkAction } from 'redux-thunk';

interface StateTree {
field: string;
}

function myFunc(action: Action | ThunkAction<void, StateTree, void>,
dispatch: Dispatch<StateTree>) {
dispatch(action); // <-- This is where the error comes from
}

...我从 TypeScript 编译器中得到这个错误:

ERROR in myFile.ts:x:y
TS2345: Argument of type 'Action | ThunkAction<void, StateTree, void>' is not assignable to parameter of type 'Action'.
Type 'ThunkAction<void, StateTree, void>' is not assignable to type 'Action'.
Property 'type' is missing in type 'ThunkAction<void, StateTree, void>'.

我认为问题是因为 redux-thunk 类型定义文件增强了 redux Dispatch 接口(interface)的方式以及 TypeScript 的无能了解要使用的 Dispatch 的定义。

有解决办法吗?

最佳答案

ThunkAction 签名随最新版本更改(现在是 ThunkAction<void, Your.Store.Definition, void, AnyAction> ),除非有一些邪恶的双重转换( action as {} as Action ),我发现更优雅的方法是将 redux dispatch 定义为 ThunkDispatch ,如下所示:

import { applyMiddleware, Store, createStore, AnyAction } from 'redux';
import logger from 'redux-logger';
import thunk, { ThunkDispatch } from 'redux-thunk';

import { Redux } from '../definitions';
import rootReducer from './reducers';
import { bootstrap } from './actions';

export default function configureStore() {

const middleware = applyMiddleware( thunk, logger );

const store: Store<Redux.Store.Definition> = createStore(rootReducer, middleware);

// Here the dispatch casting:
(store.dispatch as ThunkDispatch<Redux.Store.Definition, void, AnyAction>)( bootstrap() );

return store;

}

以防其他人正在寻找更新的答案! ^^

关于typescript - 如何分派(dispatch)一个 Action 或一个 ThunkAction(在 TypeScript 中,使用 redux-thunk)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43013204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com