Inflearn Community Q&A
Object.assign으로 값을 복사하여 concat하는 이유가 무엇인가요?
Written on
·
417
1
궁금합니다.
javascriptreact
Quiz
42% of people got it wrong. Give it a try!
React에서 상태(state)로 관리하는 배열에 변화를 줄 때(추가, 삭제, 수정 등) 직접 수정하지 않고 항상 새로운 배열을 만들어 `setState`를 사용하는 가장 중요한 이유는 무엇일까요?
메모리 사용량을 최소화하기 위해서
성능을 항상 일정하게 유지하기 위해서
자바스크립트 엔진의 최적화 기능 활용을 위해서
React가 상태 변화를 효율적으로 감지하고 화면을 업데이트하기 위해서
Answer 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++
})
});




