对于reducer,我无法在redux的代码中将reducer设置为IAppState接口。因为它出现了这个错误
Argument of type '(state: IAppState, action: any) => IAppState' is not assignable to parameter of type 'Reducer<IAppState, AnyAction>'.
Types of parameters 'state' and 'state' are incompatible.
Type 'IAppState | undefined' is not assignable to type 'IAppState'.
Type 'undefined' is not assignable to type 'IAppState'.因为我正在尝试将状态设置为IAppstate,这样我就可以递增值app.component.ts
import { Component } from '@angular/core';
import { NgRedux } from '@angular-redux/store';
import { IAppState } from './store';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'redux-demo';
counter:number =0;
constructor(private ngRedux :NgRedux<IAppState>){
}
increment (){
this.ngRedux.dispatch({type:'INCREMENT'});
}
}store.ts
export interface IAppState{
counter:number;
}
export function rootReducer(state :IAppState, action) : IAppState{
switch (action.type){
case 'INCREMENT':
return {counter: state.counter+1}
}
return state;
}发生错误的app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgReduxModule, NgRedux } from '@angular-redux/store'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { IAppState, rootReducer } from './store';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgReduxModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(ngRedux: NgRedux<IAppState>){
ngRedux.configureStore(rootReducer, {counter:0});
}
}谢谢Tuan
发布于 2021-10-19 12:14:12
该错误告诉您,您定义的reducer的签名不正确。ngRedux.configureStore的reducer参数期望的签名是(state: IAppState | undefined, action: any) => IAppState,而不是您所拥有的(state: IAppState, action: any) => IAppState
要解决此问题,请将您的缩减程序定义更改为类似以下内容:
export function rootReducer(state :IAppState | undefined, action) : IAppState {
switch (action.type){
case 'INCREMENT':
return {counter: state.counter+1}
}
return state;
}但请注意,您需要处理状态参数未定义的情况。
https://stackoverflow.com/questions/69630259
复制相似问题