강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

천재만재주벳챠님의 프로필 이미지
천재만재주벳챠

작성한 질문수

누구든지 하는 리액트: 초심자를 위한 react 핵심 강좌

배열에 데이터 삽입하기

Object.assign으로 값을 복사하여 concat하는 이유가 무엇인가요?

작성

·

379

1

궁금합니다.

답변 1

1

handleCreate = data => {
    console.log(data);
    // this.state.information.push(data); X

    const { information } = this.state;

    this.setState({
      information: information.concat(
        // 합침

        Object.assign({}, data, {
          id: this.id++
        }) // 새롭게 들어오는 데이터
      )
    });
  };

이 부분을 말씀하시는 것 같은데,

먼저 Object.assign을 하는 이유는 information의 값을 업데이트하기 위함입니다.

다음으로 concat을 하는 이유는 연락처에 있는 이전의 데이터들에 이어 붙이기 위함입니다.

만약 information: Object.assign({}, data, {id: this.id++})) 만 있다면, information에는 새로운 name과 phone만 들어가게 됩니다.

추가적으로 이렇게도 가능합니다.

const { information } = this.state;

this.setState({
  information: information.concat({
    ...data,
    id: this.id++
  })
});
천재만재주벳챠님의 프로필 이미지
천재만재주벳챠

작성한 질문수

질문하기