How to dispatch an Action or a ThunkAction (in TypeScript, with redux-thunk)?

前端 未结 4 1584
醉话见心
醉话见心 2020-12-17 15:42

Say I have code like so:

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

interface StateTree {
  field: string;
}

         


        
4条回答
  •  忘掉有多难
    2020-12-17 16:22

    ThunkAction signature changed with latest version (now is ThunkAction) and unless some evil double casting (action as {} as Action), the more elegant way I found is to define the redux dispatch as a ThunkDispatch like this:

    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 = createStore(rootReducer, middleware);
    
        // Here the dispatch casting:
        (store.dispatch as ThunkDispatch)( bootstrap() );
    
        return store;
    
    }
    

    In case someone else is looking for an updated answer! ^^

提交回复
热议问题