ReactJS-使用打字稿时createStore无法识别减速器

时间:2020-04-26 06:49:48

标签: reactjs typescript

我是Reactjs和Typescript的新手,但试图编写一个待办事项项目。但是当我调用createStore时,我在VSCode中遇到错误,并且无法解决。

任何帮助将不胜感激。

index.tsx

...
import { Provider } from "react-redux";
import { createStore } from "redux";
import itemReducer from "./reducers/itemReducer";

const store = createStore(itemReducer);
...

itemReducer.ts

...
export const ActionType = {
  INIT_ITEM : "INIT_ITEM",
  ADD_ITEM : "ADD_ITEM",
  EDIT_ITEM : "EDIT_ITEM",
  DEL_ITEM : "DEL_ITEM"
}


export interface Reduce_State {
  items: Todo_Item[];
}

export interface Reduce_Action {
  type: string;
  item: Todo_Item;
  items: Todo_Item[];
  itemIndex: number;
}


export default function itemReducer(state: Reduce_State, action: Reduce_Action) {
  if (!state) {
    state = {
      items: [],
    };
  }

  switch (action.type) {
    case ActionType.INIT_ITEM:
      return { items: action.items };
    default:
      return state;
}
...

当我将鼠标移到itemReducer时,VSCode提示我

(alias) function itemReducer(state: Reduce_State, action: Reduce_Action): Reduce_State
import itemReducer
No overload matches this call.
  Overload 1 of 2, '(reducer: Reducer<Reduce_State, Reduce_Action>, enhancer?: StoreEnhancer<unknown, unknown> | undefined): Store<Reduce_State, Reduce_Action>', gave the following error.
    Argument of type '(state: Reduce_State, action: Reduce_Action) => Reduce_State' is not assignable to parameter of type 'Reducer<Reduce_State, Reduce_Action>'.
  Overload 2 of 2, '(reducer: Reducer<Reduce_State, Reduce_Action>, preloadedState?: { items: { key: string; content: string; completed: boolean; editing: boolean; }[]; } | undefined, enhancer?: StoreEnhancer<...> | undefined): Store<...>', gave the following error.
    Argument of type '(state: Reduce_State, action: Reduce_Action) => Reduce_State' is not assignable to parameter of type 'Reducer<Reduce_State, Reduce_Action>'.ts(2769)
Peek Problem (Alt+F8)
No quick fixes available

enter image description here

当我将鼠标移到createStore时,我收到消息:

(alias) createStore<Reduce_State, Reduce_Action, unknown, unknown>(reducer: Reducer<Reduce_State, Reduce_Action>, enhancer?: StoreEnhancer<unknown, unknown> | undefined): Store<...> (+1 overload)
import createStore

enter image description here

1 个答案:

答案 0 :(得分:0)

根据错误消息判断,您有类型不匹配。我个人不知道一种减速器的解决方案,但是对我有用的是使用 combineReducers 功能。 CombineReducers函数将为您提供createStore函数所需的返回类型,并使您可以使用多个reducer。

const rootReducer = combineReducers({
   itemState: itemReducer
})

因为将React与TS和Redux一起使用是一种痛苦,所以当钩子不是主流时,我做了一个回购来帮助有此问题的人。 Maby这将为您提供帮助。

https://github.com/iamnepster/react-ts-redux-todolist