programing

유형 오류: 어레이에서 속성 1을 추가할 수 없습니다. 개체를 확장할 수 없습니다.푸시()

css3 2023. 6. 19. 21:56

유형 오류: 어레이에서 속성 1을 추가할 수 없습니다. 개체를 확장할 수 없습니다.푸시()

어레이에 데이터를 추가하려고 하는데 확장 가능한 오류가 발생하지 않습니다.

구성 요소 코드:

this._store.select(p => p.collection.workspaceCollectionPages).subscribe((data: CollectionPageDbModel[]) =>{
      if(data){
      return data.map((collectionPageDbModel)=> {

      this.collectionPages.push(collectionPageDbModel) //Getting error on this line while pushing

    });}

enter image description here

데이터 변수에 4개의 개체가 있는데, collectionPages를 밀어넣으려고 하는데, 밀어넣는 동안 확장 가능한 오류가 발생합니다.

enter image description here collection데이터를 추가해야 하는 페이지 배열

enter image description here 이 데이터를 푸시해야 합니다.

CollectionPageDb 모델:

export class CollectionPageDbModel implements IDbModel {
  public id?: number;
  public collection_version_id: number;
  public user_id?: string;
  public name: string;
  public position?: number = 0;
  public contents: string;
  public created_at?: string;
  public updated_at?: string;
  public server_id?: any;

}

누가 이 문제 해결을 도와줄 수 있습니까?

Object.assign 메서드를 사용하여 개체의 복사본을 만들고 다시 시도합니다.

this.collectionPages = Object.assign([], this.collectionPages);
this.collectionPages.push(collectionPageDbModel);

ES6 단순화된 코드는,

this.collectionPages = [...this.collectionPages, collectionPageDbModel]

데이터를 어레이에 푸시하려고 할 때 비슷한 오류 경고가 발생했습니다.제 해결책은 스프레드 연산자를 사용하는 것이었습니다.push:

let myarray: any = [];
const data = {
            answers: [],
            score: 24,
            ctime: '',
};
myarray = [...myarray, data]; // used this instead of push

다니엘이 제안한 해결책은 확실히 이 경우에 효과가 있습니다.그 이유는 모든 JS 개체가 가지고 있는 개체 설명자입니다.전화로 확인할 수 있습니다.Object.getOwnPropertyDescriptors(obj)모든 것이 객체이기 때문에 어레이에서도 작동합니다.

질문에 사용되었을 가능성이 가장 높은 NGRX 스토어 선택기는 다음을 사용하여 객체 설명자를 수정합니다.Object.defineProperties(obj)이 작업은 축소기 외부에 저장된 데이터의 변형을 방지하기 위해 수행됩니다(또한 상태가 변형되지 않고 새 데이터만 생성됨).

일반적으로 변환할 개체를 복제해야 합니다.


import { cloneDeep } from 'lodash'

// ...

constructor(private store: Store<any>) {}

someMethod() {
  let someDataFromTheStore = cloneDeep(this.store.select(selectSomeData))
  someDataFromTheStore.myArray.push('...')
}


둘다요.Object.assign그리고.cloneDeep설명자를 새 복사본으로 전송하지 않습니다.

Object.getOwnPropertyDescriptors

Object.defineProperties

이 사람은 일을 했고,

if(data){
   const result = data.map((collectionPageDbModel)=> {
      this.collectionPages.push(collectionPageDbModel) //Getting error on this line while pushing
   });
   
   return result
   // incase of async call this one will work fine
   // return Promise.all(result)
}

푸시 방식 대신 스프레드 연산자를 사용했습니다.저는 그 문제를 해결했습니다.

// Original array
const originalArray = [1, 2, 3];

// Reproduce the OP's case (prevent pushes)
Object.preventExtensions(originalArray)

// New item to add
const newItem = 4;

// Using spread operator to add the new item to the array
const newArray = [...originalArray, newItem];

console.log(newArray); // Output: [1, 2, 3, 4]

언급URL : https://stackoverflow.com/questions/52492093/typeerror-cannot-add-property-1-object-is-not-extensible-at-array-push-anon