React - 리액트를 다루는 기술(4)

Hyeonseok Jeong·2022년 10월 7일
1

React

목록 보기
6/16

state를 사용할 때 주의 사항 (배열 & 객체 업데이트 방식)

state의 값을 변경해 주기 위해서는 setState를 통해 전달받은 셰터 함수를 사용해야하는데 배열과 객체를 업데이트 하기위해서는 일반적인 업데이트 방식과는 차이가 있다

import { useState } from "react";

const Say = () => {
  const [comment, setComment] = useState("");
  const [emptyArray, setEmptyArray] = useState([]);
  let changeArray = [...emptyArray];
  // 불변성을 지켜주기 위한 스프레드 함수 사용

  const CommentValue = (e) => {
    setComment(e.target.value);
  };

  const CommentAdd = (e) => {
    // setEmptyArray((item) => [comment, ...item]) 
   	changeArray = [comment, ...emptyArray];
    setEmptyArray(changeArray);
    setComment("");
  };

  return (
    <>
      <div>{emptyArray}</div>
      <input type="text" onChange={CommentValue} value={comment} />
      <button onClick={CommentAdd}>버튼</button>
    </>
  );
};

export default Say;

위의 컴퍼넌트를 보면 let changeArray = [...emptyArray]라는 변수를 선언한 이유는 불변성을 유지하기 위해서 이다.
불변성의 중여성은 아직 지식이 부족하여 외우고만 있는 단계이며, 후에 불변성을 유지해야 되는 이유에 대해서 적어봐야한다.

스레드 함수를 사용해서 let changeArray = [...emptyArray] 를 선언해 주고

const CommentAdd = (e) => {
   	changeArray = [comment, ...emptyArray];
    setEmptyArray(changeArray);
    setComment(""); 
    // 값을 배열에 저장한후 input에 적혀있는 Text를 삭제 하기위한 함수
  };

onClick 이벤트에서 사용할 CommentAdd 함수에서 changeArray의 값을 input의 onChange 이벤트로 받아오는 value가 저장되고있는 comment 를 추가해 주었다.

그 이유는 input에 작성되는 Text의 값을 스레드 함수가 적용된 배열에 추가하여 사용자가 적은 문자열을 setEmptyArray(changeArray)와 같은 문법으로 emptyArray에 추가해 주기 위해서 이다.

(이와 같이 빈배열에 값을 저장해주는 이유는 댓글과 같은 로직을 구현하기 위함이다.)

  • setEmptyArray((item) => [comment, ...item])와 같이 위의 로직을 가독성있게 줄일 수 있다.

끝으로

이후에는 map() 메소드를 이용해서 <div></div> 안에 생성되는 배열을 차례대로 추가해 볼려고 한다.

profile
풀스텍 개발자

1개의 댓글

comment-user-thumbnail
2022년 10월 8일

정리

답글 달기