- map
- 불변성
- spread연산자
import React from "react";
import { useState } from "react";
export default function AppMentors() {
const [person, setPerson] = useState({
name: "당신",
title: "개발자",
mentors: [
{
name: "밥",
title: "시니어개발자",
},
{
name: "제임스",
title: "주니어개발자",
},
],
});
const handleNickname = () => {
const prev = prompt(`누구의 이름을 바꾸고 싶은가요?`);
const current = prompt(`이름을 무엇으로 바꾸고 싶은가요?`);
setPerson((prev) => ({
...person,
mentors: person.mentors.map((mentor) => {
if (mentor.name === prev) {
return { ...mentor, name: current };
}
return mentor;
}),
}));
};
return (
<div>
<h1>
{person.name}은 {person.title}
</h1>
<p>{person.name}의 멘토는:</p>
<ul>
{person.mentors.map((mentor, index) => (
<li key={index}>
{mentor.name} ({mentor.title})
</li>
))}
</ul>
<button onClick={handleNickname}>멘토의 이름을 바꾸기</button>
</div>
);
}
⬇️ map을 이용해 새로운 배열을 만들어서 return하는 이유 ⬇️
[AppCounter(https://programmerkokkiri.tistory.com/79) 불변성 참고]
'React(Docs) > React(Practice)' 카테고리의 다른 글
AppMentors_useReducer(구조분해할당) (0) | 2022.12.12 |
---|---|
AppMentors_추가/삭제(filter, spread연산자, key) (0) | 2022.12.11 |
AppXY_객체initialState(transform, onPointerMove) (0) | 2022.12.10 |
AppProducts_useEffect(토글, fetch, 삼항연산자, re-rendering조건) (0) | 2022.12.09 |
AppCounter_useState(불변성, 클로저, prop-drilling) (0) | 2022.12.06 |