【问题标题】:Dispatch Redux action inside Chrome Extension Background Page with TypeScript使用 TypeScript 在 Chrome 扩展背景页面中调度 Redux 操作
【发布时间】:2019-11-08 22:39:36
【问题描述】:

我正在处理 Chrome 扩展程序中的后台页面,该扩展程序使用 Thunk 异步调度 Redux 操作。动作创建者的定义如下:

export const executeProcess = (data: Data[]): ThunkAction<Promise<void>, {}, {}, AnyAction> => async (dispatch: ThunkDispatch<{}, {}, AnyAction>): Promise<void> => {

我可以使用组件的地图分派到道具从屏幕上完美地分派这个,即:

const mapDispatchToProps = {
    executeProcess: executeProcess,
};

还有:

eventTest = async () => {

        //
        //  Kickoff process
        await this.props.executeProcess(this.props.data);
    };

还有 JSX 本身:

<button onClick={this.eventTest}>EVENT TESTER</button>

我正在尝试在后台页面中做类似的事情,特别是:

chrome.alarms.onAlarm.addListener(async () => {
await store.dispatch(executeProcess(store.getState().data))
});

这样做会引发以下 TS 错误:

Property 'type' is missing in type 'ThunkAction<Promise<void>, {}, {}, AnyAction>' but required in type 'AnyAction'.

我正在使用 webext-redux NPM 包,以便我能够在屏幕和后台页面中使用商店,并且能够从后台页面中的商店中读取,但是无法调度操作. dispatch 定义需要一个 AnyAction 类型的实例,即:

export interface AnyAction extends Action

但是 ThunkAction 自然地从 Action 扩展而来:

export type ThunkAction<R, S, E, A extends Action> = (

有什么方法可以更改动作创建者的签名,以便调度在屏幕和背景页面上都没有问题?

我如何使用(上述 NPM)声明我的 store.ts 如下:

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
let store: Store<RootState>;

store = createStoreWithMiddleware(reducers, loadState());
store.subscribe(throttle(() => {
    saveState(store.getState())
}, 1000));

wrapStore(store, {
    portName: constants.ApplicationName,
});

export {store};

【问题讨论】:

    标签: javascript reactjs typescript google-chrome-extension redux


    【解决方案1】:

    实现这项工作的解决方案/kludge,如下定义商店:

    let store: Store<RootState, any>;
    

    解决如下:

    export interface Store<S = any, A extends Action = AnyAction> {
    

    而不是这个:

    let store: Store<RootState>;
    

    理想情况下会传递 ThunkAction 而不是任何类型,但会遇到泛型参数问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-27
      • 2011-03-03
      • 2014-10-19
      • 2012-03-28
      • 1970-01-01
      相关资源
      最近更新 更多