如何在angular5 app中显示redux商店的商品?

时间:2017-12-09 06:14:53

标签: angular redux angular-redux

我有一个angular5组件,我正在尝试与reduxstore连接,它看起来像这样:

import { Component } from '@angular/core';
import { NgRedux, select, DevToolsExtension } from '@angular-redux/store';
import { TodoActions } from './actions';
import { AppState, INITIAL_STATE, rootReducer } from './store';
import {Observable} from "rxjs/Observable";

@Component({
  selector: 'app-root',
  template: `    
    <input type="text" #edit />
    <button (click)="actions.add({data:edit,action:'ADD'})">add</button>
    <p>The list is:</p>
    <ul>
      <li *ngFor="let item of (items | async)">
        {{item}}
      </li>
    </ul>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  @select() readonly items$: Observable<string[]>;

  constructor(
    ngRedux: NgRedux<AppState>,
    devTools: DevToolsExtension,
    private actions: TodoActions) {

    ngRedux.configureStore(
      rootReducer,
      INITIAL_STATE,
      null,
      devTools.isEnabled() ? [ devTools.enhancer() ] : []);
  }
}

问题是我无法在列表中显示项目。这是rootreducer:

import {Action} from 'redux';
import {TodoActions} from './actions';

export interface AppState {
  items: string[];
}
export const INITIAL_STATE: AppState = {items: []};

export function rootReducer(state: AppState, action: Action): AppState {
  switch (action.type) {
    case TodoActions.ADD:
      var newstate = state;
      newstate.items.push(action.data.data.value);
      return newstate;
  }
  ;

default:
  return state;
}
}

如何显示项目?看起来第一个项目从redux-console添加到状态。这也是githublink

1 个答案:

答案 0 :(得分:1)

这看起来不太正确:

  var newstate = state;
  newstate.items.push(action.data.data.value);
  return newstate;

您实际上并未创建新数组或副本:newstatestate都是相同的数组,因此您可能最好将新数组返回浅 - 克隆:

export function rootReducer(state: AppState, action): AppState {
  switch (action.type) {
    case TodoActions.ADD:
      return {
        ...state,
        items: [
          ...state.items,
          action.data.value
        ]
      }

    default:
      return state;
  }
}

您可能会注意到我已将类型说明符拉出action。我不确定将Action指定为操作类型是有意义的,在大多数示例代码中我都看到过无类型传递:

export function rootReducer(state: AppState, action): AppState {

这样可以避免TS抱怨类型data上缺少Action。或者,您可以为您编写的每个reducer定义自定义操作类型。

一旦你过了那个,我认为你没有看到任何项目的原因是因为你在items$装饰器中命名了数组@select。所以:

@Component({
  selector: 'app-root',
  template: `    
    <input type="text" #edit />
    <button (click)="actions.add({value:edit.value,action:'ADD'})">add</button>
    <p>The list is:</p>
    <ul>
      <li *ngFor="let item of (items$ | async)">
        {{item}}
      </li>
    </ul>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  @select() readonly items$: Observable<string[]>;

效果更好。注意我稍微调整了按钮定义以避免传递整个输入,因为您只需要value