我正在尝试使用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;
最佳答案
您要通过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';