首页 > 解决方案 > NGRX 商店。无法分配给对象“[对象数组]”的只读属性“18”

问题描述

当我尝试创建 ngrx 商店时,我遇到了 7 个错误。

TypeError:无法分配给对象“[object Array]”的只读属性“18”| TypeError:无法分配给对象“[object Object]”的只读属性“incompleteFirstPass”| TypeError:无法读取未定义的属性(读取“值”)

减速器.ts

import { createReducer, on } from '@ngrx/store';
import { Fields } from '../fields.model';

import { addAllFields } from './fields.action';

export const initialState: Readonly<Fields> = {
  arrStart: [],
  arrEnd: [],
};

export const fieldsReducer = createReducer(
  initialState,
  on(addAllFields, (state, { extArr }) => {
    return { ...state, arrStart: extArr };
  })
);

动作.ts

import { TemplateRef } from '@angular/core';
import { createAction, props } from '@ngrx/store';

export const addAllFields = createAction(
  '[Fields Array]Add fields to starting array',
  props<{ extArr: TemplateRef<any>[] }>()
);

字段.model.ts

import { TemplateRef } from '@angular/core';

export interface Fields {
  arrStart: TemplateRef<any>[] | null;
  arrEnd: TemplateRef<any>[] | null;
}

我知道状态必须是不可变的,因此,我返回当前状态的副本。

我的组件中有调度,一定有问题。console.log(fieldsArr) 返回 2 TemplateRef

constructor(private store: Store) {}

  ngOnInit(): void {}

  ngAfterViewInit() {
    const fieldsArr: TemplateRef<any>[] = [this.inputField, this.textareaField];
    console.log(fieldsArr);

    this.store.dispatch(addAllFields({ extArr: fieldsArr }));
  }

标签: javascriptangulartypescriptfrontendngrx

解决方案


问题可能是TemplateRef,因为这些被发送到商店,这些将被冻结。我不是 100% 确定,但我的猜测是 Angular 会TemplateRef改变 on change detection。因为这与商店冻结的实例相同,所以会引发此错误。


推荐阅读