Angular 5和angular-rdux / store

时间:2018-02-27 18:59:23

标签: angular redux angular5 angular-redux ngredux

我已经安装了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

有没有人遇到过这个错误?你有什么决议吗?

先谢谢。

1 个答案:

答案 0 :(得分: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