state 값을 바꿔줄때 push 와 concat의 차이를 알아보자
const arr = [1,2];
arr.push(3);
console.log(arr); // [1,2,3]
위의 코드를 확인해 보면 arr 배열의 push(3)를 하고 arr 결과를 확인해보면 arr 자체가 변경된 걸 확인할 수 있다.
const arr = [1,2];
let res = arr.concat(3);
console.log(arr) // [1,2]
console.log(res) // [1,2,3]
위의 코드를 확인해보면 res라는 변수에 arr.concat(3)을 하고, 먼저 arr 값을 확인하면 기존 배열이 그대로 나오고 concat를 사용한 res 값을 확인해보면 [1,2,3]이 나오는 걸 확인할 수 있다.
addComment = e => {
e.preventDefault();
const { commentList } = this.state;
const newComment = {
id: commentList.length + 1,
userId: 'K_seung_chan',
text: this.state.commentValue,
};
this.setState({
commentList: [...commentList, newComment],
commentValue: '',
});
};
위 코드를 보면 concat 함수인 ... 를 사용하여 기존 배열을 유지하고 새로운 배열을 만들어 주었다. 원본은 바뀌지 않는다라는것을 보여주었다. react에서는 immutable 이라고 한다.