我正在尝试使用react + redux + typescript设置前端环境,但是我正在努力使其与CombineReducers一起使用。
我收到一个错误:类型的参数不能分配给类型'ReducersMapObject'的参数。请参阅代码下方的完整错误消息。

状态:(类型/index.tsx)

export namespace StoreState {

  export type Enthusiasm = {
    languageName: string;
    enthusiasmLevel: number;
  }

  export type All = {
    enthusiasm: Enthusiasm
  }
}

商店:(store.tsx)
import { createStore } from 'redux';
import reducers from './reducers/index';
import { StoreState } from './types/index';

let devtools: any = window['devToolsExtension'] ? window['devToolsExtension']() : (f:any)=>f;

const Store = createStore<StoreState.All>(reducers, devtools);
export default Store;

减少器:(/reducers/HelloReducer.tsx)
    import { EnthusiasmAction } from '../actions';
    import { StoreState } from '../types/index';
    import { INCREMENT_ENTHUSIASM, DECREMENT_ENTHUSIASM } from '../constants/index';

    export const enthusiasm = (state: StoreState.Enthusiasm,
action: EnthusiasmAction): StoreState.Enthusiasm => {
      switch (action.type) {
        case INCREMENT_ENTHUSIASM:
            return { ...state, enthusiasmLevel: state.enthusiasmLevel + 1 };
        case DECREMENT_ENTHUSIASM:
            return { ...state, enthusiasmLevel: Math.max(1, state.enthusiasmLevel - 1) };
        default:
            return state;
     }
   }

组合 reducer (/reducers/index.tsx)
import { StoreState } from '../types/index';
import * as enthusiasmReducer from './HelloReducer';

import { combineReducers } from 'redux';

const reducer = combineReducers<StoreState.All>({
    enthusiasm: enthusiasmReducer
});

export default reducer;

reactjs - 带Typescript的CombineReducers返回错误 &#34;Argument of type is not assignable to parameter of type &#39; ReducersMapObject&#39;“-LMLPHP

最佳答案

您要通过HelloReducer的所有导出而不是只是reducer来传递对象。有几种方法可以修复它。您可以选择 reducer :

const reducer = combineReducers<StoreState.All>({
    enthusiasm: enthusiasmReducer.enthusiasm
});

或仅导入 reducer :
import {enthusiasm} from './HelloReducer';
..
const reducer = combineReducers({enthusiasm});

或将export default enthusiasm;添加到HelloReducer.tsx并将导入更改为
import enthusiasmReducer from './HelloReducer';

10-08 15:47