reactjs Redux createStorreproduces an error< StoreState>:需要4个类型参数,但得到了1个

xxslljrj  于 2023-05-28  发布在  React
关注(0)|答案(2)|浏览(140)

我正在关注一个TypeScript-React-Starter tutorial,并在src/index.tsx中创建一个商店。从教程中,

const store = createStore<StoreState>(enthusiasm, {
  enthusiasmLevel: 1,
  languageName: 'I\'m fluent in Math and Klingon'
});

产生错误

Expected 4 type arguments, but got 1.

Issue #136建议使用

import { EnthusiasmAction } from './actions/index';

const store = createStore<StoreState, EnthusiasmAction, any, any>(enthusiasm, {
  enthusiasmLevel: 1,
  languageName: 'I\'m fluent in Math and Klingon'
});

但这会产生另一个错误:

Argument of type '(state: StoreState, action: EnthusiasmAction) => StoreState' is not assignable to parameter of type 'Reducer<StoreState, EnthusiasmAction>'.
Types of parameters 'state' and 'state' are incompatible.
  Type 'StoreState | undefined' is not assignable to type 'StoreState'.
    Type 'undefined' is not assignable to type 'StoreState'.

这个问题已经解决了,但从那以后其他人也遇到了同样的问题。

如何创建我的商店?

4uqofj5v

4uqofj5v1#

const store = createStore<StoreState>(enthusiasm, {
  enthusiasmLevel: 1,
  languageName: 'I\'m fluent in Math and Klingon'
});

产生错误

Expected 4 type arguments, but got 1.

这是由于教程使用的是Redux 3.7.2,而我使用的是Redux 4.0.1。

解决方案#1

我安装了Redux 3.7.2:

npm install redux@3.7.2

由于我使用的是TypeScript-React-Starter tutorial,这是本教程中最好的解决方案。

溶液#2

我修改了createStore()函数,按照错误消息的建议接受4个类型参数:

const store = createStore<StoreState, Action<any>, unknown, unknown>(enthusiasm, {
  enthusiasmLevel: 1,
  languageName: 'I\'m fluent in Math and Klingon',
});

现在我可以使用Redux 4.0.1继续tutorial。:—)

kmb7vmvb

kmb7vmvb2#

在创建存储区时,尝试在reducer中创建初始状态。应该能用

export interface IStoreState {
    languageName: string;
    enthusiasmLevel: number
}
const initState: IStoreState = {
    languageName: "TypeScript",
    enthusiasmLevel: 0
}

相关问题