nested 객체 상태관리

유석현(SeokHyun Yu)·2022년 11월 21일
0

React

목록 보기
9/21
post-thumbnail

AppMentor.jsx

import React, { useState } from "react";

export default function AppMentor(props) {
  const [person, setPerson] = useState({
    name: "엘리",
    title: "개발자",
    mentor: {
      name: "밥",
      title: "시니어개발자",
    },
  });

  return (
    <div>
      <h1>
        {person.name}{person.title}
      </h1>
      <p>
        {person.name}의 멘토는 {person.mentor.name} ({person.mentor.title})
      </p>
      <button
        onClick={() => {
          const name = prompt(`what's your mentor's name?`);
          setPerson((prev) => {
            return {
              ...prev,
              mentor: {
                ...prev.mentor,
                name,
              },
            };
          });
        }}
      >
        멘토 이름 바꾸기
      </button>
      <button
        onClick={() => {
          const title = prompt(`what's your mentor's title?`);
          setPerson((prev) => {
            return {
              ...prev,
              mentor: {
                ...prev.mentor,
                title,
              },
            };
          });
        }}
      >
        멘토 타이틀 바꾸기
      </button>
    </div>
  );
}
profile
Backend Engineer

0개의 댓글