[공식문서 공략] Choosing the State Structure

2023. 9. 13. 17:32Trip to React

state 구조화 한번도 생각해보지 않았던 부분이다.

초창기 값이 무시된다는 걸 알 수 있도록 명명한다. 초기에만 들어오고 state color에 값이 들어오면 수정됨 

 

이런 실수는 할 수 있을 것 같음;

 

지금 initialItems 가 items에 들어가 있는데 items[0]가 아래 state로 관리되고 있음. 중복되는데 input에 변해도 아래 ui가 안변함

 

선택된 아이템의 아이디를 찾아서 value를 변경시켜 다시 저장 그리고 리렌더링 되고 아래 메시지도 변경

3번 파고들어감
키. 값으로 정규화

import { useState } from 'react';
import { initialTravelPlan } from './places.js';

export default function TravelPlan() {
  const [plan, setPlan] = useState(initialTravelPlan);

  function handleComplete(parentId, childId) {
    const parent = plan[parentId];
    // Create a new version of the parent place
    // that doesn't include this child ID.
    const nextParent = {
      ...parent,
      childIds: parent.childIds
        .filter(id => id !== childId)
    };
    // Update the root state object...
    setPlan({
      ...plan,
      // ...so that it has the updated parent.
      [parentId]: nextParent
    });
  }

  const root = plan[0];
  const planetIds = root.childIds;
  return (
    <>
      <h2>Places to visit</h2>
      <ol>
        {planetIds.map(id => (
          <PlaceTree
            key={id}
            id={id}
            parentId={0}
            placesById={plan}
            onComplete={handleComplete}
          />
        ))}
      </ol>
    </>
  );
}

function PlaceTree({ id, parentId, placesById, onComplete }) {
  const place = placesById[id];
  const childIds = place.childIds;
  return (
    <li>
      {place.title}
      <button onClick={() => {
        onComplete(parentId, id);
      }}>
        Complete
      </button>
      {childIds.length > 0 &&
        <ol>
          {childIds.map(childId => (
            <PlaceTree
              key={childId}
              id={childId}
              parentId={id}
              placesById={placesById}
              onComplete={onComplete}
            />
          ))}
        </ol>
      }
    </li>
  );
}

굳이 파일을 나눌 필요가 없겠다. 나는 리스트를 따로 빼서 작성했었는데.