开发者问题收集

Angular NGRX 在调度到状态时出现错误

2019-12-14
1081

我第一次使用 Ngrx,虽然它相对简单,但在调度到状态时出现错误。当用户打开应用程序时,他需要输入他的名字并提交,下一个屏幕应该显示“问候 {{ username }} ”。用户提交后,我收到此错误 -> core.js:6014 ERROR TypeError: 对象不可迭代(无法读取属性 Symbol(Symbol.iterator))

感谢您的帮助

import { Action } from '@ngrx/store';
import { UserName, WishListItem } from 'src/model/name.model';

export enum AddToStateActionType{
    ADD_NAME = '[ADD_NAME] add name',
    ADD_TO_WISHLIST = '[ADD_TO_WISHLIST] add to wishlist'
}

export class AddWelcomeNameAction implements Action {
    readonly type = AddToStateActionType.ADD_NAME;

    constructor(public payload: UserName){}
}

export class AddToWishList implements Action {
    readonly type = AddToStateActionType.ADD_TO_WISHLIST;

    constructor(public payload: WishListItem){}
}

export type UserAction = AddWelcomeNameAction | AddToWishList ;
<!--Reducer-->

import {AddToStateActionType, UserAction} from './../action/action';
import { UserName, WishListItem } from 'src/model/name.model';

const initialState: any = {
    name: '',
    wishlist: []
};


export function reducer(state: any = initialState, action: any) {
    switch(action.type) {
        case AddToStateActionType.ADD_NAME:
            return [...state, action.payload.name];
        case AddToStateActionType.ADD_TO_WISHLIST:
            return [...state. action.payload.wishlist];
    default:
        return state;
    }
}
<!--AppState-->

import { UserName, WishListItem } from 'src/model/name.model';

export interface AppState {
    readonly username: UserName;
    readonly wishlist: Array<WishListItem> ;
  }
<!--Welcome component-->

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Store } from '@ngrx/store';
import { AppState } from '../app.state/app.state';
import * as Actions from '../../action/action';
import {Router} from '@angular/router';
import { UserName } from 'src/model/name.model';

@Component({
  selector: 'app-welcome',
  templateUrl: './welcome.component.html',
  styleUrls: ['./welcome.component.css']
})
export class WelcomeComponent implements OnInit {
  userName: UserName = {name: ''};

  profileForm = new FormGroup({
    userName: new FormControl(''),
  });
  constructor(private store: Store<AppState>, private router: Router) { }

  ngOnInit() {
  }

  onSubmit() {
   this.store.dispatch(new Actions.AddWelcomeNameAction({name: this.profileForm.value}));
   this.router.navigate(['/search']);
  }

}
2个回答

在这两种情况下,问题都出在你的减速器上。

在您的代码中:

export function reducer(state: any = initialState, action: any) {
    switch(action.type) {
        case AddToStateActionType.ADD_NAME:
            return [...state, action.payload.name];
        case AddToStateActionType.ADD_TO_WISHLIST:
            return [...state. action.payload.wishlist];
    default:
        return state;
    }
}

您错误地应用了扩展运算符,导致两个问题:

数组扩展运算符 :您正在应用数组扩展运算符: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

[...state, action.payload.name]; // This is an array

此运算符的工作方式如下:

let a = [1, 2, 3];
let b = 4;
let c = [...a, b]; // Here we will add each item of a and then b resulting in c = [1, 2, 3, 4]

因此,运行时将尝试“迭代”状态,但状态是一个对象,而不是一个数组。这是第一个错误。

Reducer 返回类型 :默认情况下,您会按预期返回原始状态,但在这两种情况下,您实际上都会返回一个数组。

作为一种良好做法,如果您明确指定 Reducer 的返回类型,您将看到 TypeScript 如何抱怨它。

解决方案: 要修复您的代码,您应该将 Reducer 重写为类似以下内容:

case AddToStateActionType.ADD_NAME:
    // Here you return a copy of state and overwrite the name property.
    return { 
        ...state,
        name: action.payload.name,
    };
case AddToStateActionType.ADD_TO_WISHLIST:
    // Here you return a copy of state and overwrite the wishlist property with the same elements + the new one.
    return {
        ...state,
        wishlist: [...state.wishlist, action.payload.wishlist]
    };
mdarefull
2019-12-14

您的状态类型不一致。 initialState 是对象,但 Reducer 返回数组。如果您在控制台中尝试此代码,您会得到相同的错误:

const a = {name: "", wishlist: []}
const b = [...a]

TypeError: a is not iterable

Ivan
2019-12-14