首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular Redux,无法将IAppState设置为状态

Angular Redux,无法将IAppState设置为状态
EN

Stack Overflow用户
提问于 2021-10-19 11:47:44
回答 1查看 53关注 0票数 0

对于reducer,我无法在redux的代码中将reducer设置为IAppState接口。因为它出现了这个错误

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

发布于 2021-10-19 12:14:12

该错误告诉您,您定义的reducer的签名不正确。ngRedux.configureStore的reducer参数期望的签名是(state: IAppState | undefined, action: any) => IAppState,而不是您所拥有的(state: IAppState, action: any) => IAppState

要解决此问题,请将您的缩减程序定义更改为类似以下内容:

代码语言:javascript
复制
export function rootReducer(state :IAppState | undefined, action) : IAppState {
    switch (action.type){
        case 'INCREMENT':
            return {counter: state.counter+1}
    }
    return state;
}

但请注意,您需要处理状态参数未定义的情况。

代码语言:javascript
复制
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69630259

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档