React(Docs)/React(Practice)

AppMentors_배열상태 관리(불변성, map, spread연산자)

ecoEarth 2022. 12. 11. 15:40
  • 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) 불변성 참고]