首页 > 解决方案 > NgRx createReducer() 和 on() 给出错误

问题描述

我是新的。到 NgRx。

当我尝试使用创建减速器createReducer()时出现错误Expected 4 arguments, but got 2. 当我尝试将第 3 和第 4 个参数作为 null 传递时,出现错误

Argument of type '(state: any, { updatedValue }: any) => any' is not assignable to parameter of type 'readonly ActionCreator<string, FunctionWithParametersType<any[], object>>[]'.
  Type '(state: any, { updatedValue }: any) => any' is missing the following properties from type 'readonly ActionCreator<string, FunctionWithParametersType<any[], object>>[]': concat, join, slice, indexOf, and 15 more.ts(2345)

减速机代码

import { createReducer, on, State, Action } from '@ngrx/store';

import { Ingredient } from '../../shared/ingredient.model';
import * as ShoppingListAction from './shopping-list.action';

export const initialState = {
  ingredients: [
    new Ingredient('Apples', 5),
    new Ingredient('Tomatoes', 10),
  ]
}

export const shoppingListReducer = createReducer(
  initialState,
  on(
    'ADD_INGREDIENT',
    (state: any, { updatedValue }: any) => ({ ...state, prop: updatedValue }),
    null,
    null
  )
);

动作代码

import { createAction, props } from '@ngrx/store';
import { Ingredient } from '../../shared/ingredient.model';


export const ADD_INGREDIENT = 'ADD_INGREDIENT';

export const AddIngredient = createAction(
  ADD_INGREDIENT,
  props<Ingredient>()
);

app.module.ts

import { SharedModule } from './shared/shared.module';
import { CoreModule } from './core.module';
import { LoggingService } from './logging.service';

// Store
import { shoppingListReducer } from './shopping-list/store/shopping-list.reducer';

@NgModule({
  declarations: [AppComponent, HeaderComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule,
    SharedModule,
    CoreModule,
    StoreModule.forRoot({ 'slReduce': shoppingListReducer })
  ],
  bootstrap: [AppComponent],
  // providers: [LoggingService]
})
export class AppModule {}

包.json

"dependencies": {
    "@angular/animations": "^11.2.1",
    "@angular/common": "^11.2.1",
    "@angular/compiler": "^11.2.1",
    "@angular/core": "^11.2.1",
    "@angular/forms": "^11.2.1",
    "@angular/platform-browser": "^11.2.1",
    "@angular/platform-browser-dynamic": "^11.2.1",
    "@angular/router": "^11.2.1",
    "@ngrx/store": "^11.0.1",
    "bootstrap": "3.3.7",
    "core-js": "^3.1.2",
    "rxjs": "^6.0.0",
    "tslib": "^2.0.0",
    "zone.js": "~0.11.3"
  }

标签: javascriptangularngrxngrx-store

解决方案


我在我的 IDE 中看到了这个错误,以及与 @ngrx/store 相关的其他一些奇怪的类型相关错误,但项目编译得很好。

我已将使用 @ngrx 的项目中的 typescript 版本升级到最新版本(当时为 v4.3.4),但我的工作区包含其他几个项目,并且我的 IDE(我正在使用 WebStorm)typescript 语言服务配置为使用安装在我的其他项目之一上的旧版打字稿。将 IDE 打字稿服务配置为使用较新的打字稿版本后,错误就消失了。

所以就我而言,这是几件不同的事情——首先,我需要为我的项目升级打字稿版本,这些项目使用@ngrx 以使用@ngrx 正在使用的一些新语言功能。然后,我还必须确保我的 IDE 的 typescript 语言服务正在使用该版本,或者至少是相当新的 typescript 版本,以避免在编辑器窗口中看到虚假错误。


推荐阅读