Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

React - learn - Updating Objects in State, Updating Arrays in State (객체, 배열로 상태 업데이트하기) 본문

React

React - learn - Updating Objects in State, Updating Arrays in State (객체, 배열로 상태 업데이트하기)

보람- 2023. 11. 29. 17:33

 

 

1. Updating Objects in State (마우스 포인터)

 

https://react.dev/learn/updating-objects-in-state

import { useState } from "react";

export default function MovingDot() {
  const [position, setPosition] = useState({
    x: 0,
    y: 0,
  });

  return (
    <div
      onPointerMove={(e) => {
        setPosition({
          x: e.clientX,
          y: e.clientY,
        });
      }}
      style={{
        position: "relative",
        width: "100vw",
        height: "100vh",
      }}
    >
      <div
        style={{
          position: "absolute",
          backgroundColor: "gold",
          borderRadius: "50%",
          transform: `translate(${position.x}px, ${position.y}px)`,
          left: -10,
          top: -10,
          width: 20,
          height: 20,
        }}
      />
    </div>
  );
}

- 상태를 읽기전용으로 처리

- 새로운 객체를 만들어서 설정함수에 전달해서 다시 랜더링하게하기

 

 

 

2. Updating Arrays in State

 

https://react.dev/learn/updating-arrays-in-state#updating-arrays-without-mutation

- 배열 역시 객체이므로 react에서 상태의 배열을 읽기전용으로 처리해야한다.

- 배열 내부의 항목을 재할당해서는 안되며 push, pop 같은 배열을 변경하는 메서드를 사용하면 안된다.

- 대신 배열을 업데이트 할때마다 상태 설정 함수에 새 배열을 전달해야한다! 

  → filter, map 메서드 사용하기

 

 

 

2-1 과제 : 장바구니 항목 업데이트 (map 사용하기)

import { useState } from "react";

const initialProducts = [
  {
    id: 0,
    name: "Baklava",
    count: 1,
  },
  {
    id: 1,
    name: "Cheese",
    count: 5,
  },
  {
    id: 2,
    name: "Spaghetti",
    count: 2,
  },
];

export default function ShoppingCart() {
  const [products, setProducts] = useState(initialProducts);

  function handleIncreaseClick(productId) {
    setProducts(
      products.map((product) => {
        if (product.id === productId) {
          return {
            ...product,
            count: product.count + 1,
          };
        } else {
          return product;
        }
      }),
    );
  }

  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>
          {product.name} (<b>{product.count}</b>)
          <button
            onClick={() => {
              handleIncreaseClick(product.id);
            }}
          >
            +
          </button>
        </li>
      ))}
    </ul>
  );
}

 

2-2 과제 : 장바구니 항목 제거하기 (map, filter 사용하기)

 


※ immer를 사용하면 코드를 간결하게 유지할수있다고한다... ?