
멘토 이름 바꾸기 버튼을 눌러서 새로운 멘토 이름을 입력하면 화면에 바로 보이고 싶음
const [person, setPerson] = useState({
name: '엘리',
title: '개발자',
mentor: {
name: '밥',
title: '시니어개발자',
},
});
중첩 객체로 선언되어 있는 상태
onClick={() => {
const name = prompt(`what's your mentor's name?`);
setPerson((prev) => ({
...prev,
mentor: {
name: name,
title: prev.mentor.title,
},
}));
}}
버튼을 누르면 setPerson에 변경된 데이터를 포함한 person 정보를 넣어줌
mentor 부분만 바뀌니까 이전 데이터는 …prev 로 가져옴
mentor 부분에서 새로운 데이터로 변경되는 name, 이전 데이터와 동일한 title은 prev.mentor.title 로 데이터를 직접 변경해줌
onClick={() => {
const name = prompt(`what's your mentor's name?`);
setPerson((prev) => ({
...prev,
mentor: { ...prev, name},
}));
}}
prev를 아예 복사해왔던 것처럼 mentor 데이터도 …prev로 복사한 뒤에
새로운 데이터로 변경되는 name만 뒤에 추가해줌
덮어씌워지니까 결국 새로운 데이터인 name으로 변경됨