redux type '(状态:状态,动作:动作)=>状态"不能分配给类型为“Reducer〈状态,动作>”的参数< any>

093gszye  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(169)

目前,我正在尝试使用以下代码创建redux存储。

import { createStore, Action } from "redux";
interface State {
  page: string;
}

const reducer = (state: State, action: Action) => {
  return state;
};
export const store = createStore(reducer);

但是在createStore函数中出现错误,告诉我

No overload matches this call.
  Overload 1 of 2, '(reducer: Reducer<State, Action<any>>, enhancer?: StoreEnhancer<unknown, unknown> | undefined): Store<State, Action<...>>', gave the following error.
    Argument of type '(state: State, action: Action) => State' is not assignable to parameter of type 'Reducer<State, Action<any>>'.
      Types of parameters 'state' and 'state' are incompatible.
        Type 'State | undefined' is not assignable to type 'State'.
          Type 'undefined' is not assignable to type 'State'.
  Overload 2 of 2, '(reducer: Reducer<State, Action<any>>, preloadedState?: { page: string; } | undefined, enhancer?: StoreEnhancer<unknown, {}> | undefined): Store<...>', gave the following error.
    Argument of type '(state: State, action: Action) => State' is not assignable to parameter of type 'Reducer<State, Action<any>>'.

还原版本为^4.1.0

zzwlnbp8

zzwlnbp81#

根据Reducer的定义,传入状态可以是undefined,因此您应该如下声明reducer:

const reducer = (state: State | undefined, action: Action): State => {
  return state ?? { page: 'default' }
}
db2dz4w8

db2dz4w82#

我有一个类似的问题,我解决了它的设置类型的行动在减速器功能如下:

const reducer = (state: State, action: Action | AnyAction) => {
  return state;
};

我添加了任何操作

相关问题