本文介绍了带有 Typescript 的 CombineReducers 返回错误“类型的参数不可分配给类型为“ReducersMapObject"的参数";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to setup a front-end environment with react + redux + typescript, but I am struggling to get it work with combineReducers.I get an error: Argument of type is not assignable to parameter of type 'ReducersMapObject'. See the full error message below the code.

状态:(types/index.tsx)

STATE: (types/index.tsx)

export namespace StoreState {

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

  export type All = {
    enthusiasm: Enthusiasm
  }
}

商店:(store.tsx)

STORE: (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)

REDUCER: (/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;
     }
   }

组合减速器 (/reducers/index.tsx)

COMBINE REDUCERS (/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;

推荐答案

您正在传递带有所有 HelloReducer 导出的对象,而不仅仅是 reducer.有几种方法可以修复它.您可以选择减速器:

You're passing the object with all of HelloReducer's exports instead of just the reducer. There's a couple of ways to fix it. You can select the reducer:

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

或者只导入reducer:

or import only the reducer:

import {enthusiasm} from './HelloReducer';
..
const reducer = combineReducers({enthusiasm});

或者在HelloReducer.tsx中添加export default Interest;并将import改为

or add export default enthusiasm; to HelloReducer.tsx and change the import to

import enthusiasmReducer from './HelloReducer';

这篇关于带有 Typescript 的 CombineReducers 返回错误“类型的参数不可分配给类型为“ReducersMapObject"的参数";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 05:35