0

我已经安装了 Angular 5,

"@angular-redux/store": "^7.1.0",

"redux": "^3.7.2",

这是我的 app.module.ts 构造函数:

constructor(ngRedux: NgRedux<IAppState>) {
 console.log('Configuring ngRedux');
 ngRedux.configureStore(rootReducer, INITIAL_STATE);
 }

这是我的 store.ts 文件:

import { INCREMENT } from './actions';
export interface IAppState {
 counter: number;
}
export const INITIAL_STATE: IAppState = {
 counter: 0
};
export function rootReducer(state: IAppState, action): IAppState {
 console.log(state);
 switch (action.type) {
 case INCREMENT:
 return {
 counter: state.counter + 1
 };
 }
}

和我的 app.component.ts 文件:

import { Component, ChangeDetectionStrategy } from '@angular/core';
import { NgRedux, select } from '@angular-redux/store';
import { IAppState } from './store';
import { INCREMENT } from './actions';
@Component({
 changeDetection: ChangeDetectionStrategy.OnPush,
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'Redux';
 @select() counter;
 constructor(private ngRedux: NgRedux<IAppState>) {
 ngRedux.subscribe(() => {
 console.log(ngRedux.getState());
 });
 }
 increment() {
 this.ngRedux.dispatch({
 type: INCREMENT
 });
 }
}

第一个错误:

当我单击增量按钮时,我得到表达式在检查错误后已更改。所以用谷歌搜索并添加

changeDetection: ChangeDetectionStrategy.OnPush,
所以表达式在检查错误解决后发生了变化。但在此之后,当我点击增量时,我得到了 NAN。这是控制台输出:

Configuring ngRedux - Message from AppModule constructor
{counter: 0} - Message from rootReducer - First Time while initializing
--After hitting increment button
{} - Empty Object from rootReducer
{counter: NaN} - value of ngRedux.getState() in app.component.ts constructor

有人遇到过这个错误吗?你有解决办法吗?

提前致谢。

4

1 回答 1

0

在您的“rootReducer”函数中,缺少返回(新)状态。应该是这样的

export function rootReducer(state: IAppState, action): IAppState {
    ...
    return state; // we care!
}

来自https://github.com/angular-redux/store/blob/master/articles/intro-tutorial.md

于 2018-10-29T20:38:01.513 回答