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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Reactjs-createStore在使用打字稿时无法识别减速器相关的知识,希望对你有一定的参考价值。

我是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

答案

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

const rootReducer = combineReducers(
   itemState: itemReducer
)

由于当钩子不是主流时,在React和TS和Redux上使用React是很痛苦的,所以我进行了回购,以帮助那些对此主题有疑问的人。 Maby这将为您提供帮助。

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

以上是关于Reactjs-createStore在使用打字稿时无法识别减速器的主要内容,如果未能解决你的问题,请参考以下文章

使用猫鼬模型设置打字稿

在打字稿组件中使用'import * as'会出错 -

打字稿捆绑器到打字稿文件

为啥我们在打字稿中使用 HTMLInputElement?

在条件中使用打字稿变量

打字稿打字,打字文件夹是啥