【问题标题】:Angular 5 and angular-rdux/storeAngular 5 和 angular-redux/store
【发布时间】:2018-02-27 18:59:22
【问题描述】:

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

第一个错误:

当我点击增量按钮时,我得到表达式在检查错误后已更改。于是google了一下,添加了

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

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

提前致谢。

【问题讨论】:

    标签: angular redux angular5 angular-redux ngredux


    【解决方案1】:

    在您的“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-03-15
      • 2019-08-29
      • 2019-06-16
      • 2021-01-12
      • 2022-01-14
      • 2017-11-21
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      相关资源
      最近更新 更多