말하는 컴공감자의 텃밭

React - State, Props, 구조분해할당 본문

프론트엔드/React

React - State, Props, 구조분해할당

현콩 2024. 1. 31. 17:20
728x90

React

State와 Props ?

 

- State 

부모 컴포넌트에서 자녀 컴포터는로 데이터를 보내는게 아니라 해당 컴포넌트 내부에서 데이터를 전달하고자 할때 사용. 

ex) 검색창에서 글을 입력할때 글이 변하는것은 state를 변경시킨다.

State는 변경가능하다.

State가 변하면 re-render된다.

state = {
message : '',
attachFile : undefined,
openMenu : false,
};

 

 

- Props

프로퍼티 Properties의 줄임말로 상속하는 부모 컴포넌트로부터 자녀 컴포넌트에 데이터 등을 전달하는 방법이다.

읽기 전용으로 자녀 컴포넌트에서는 변하지 않는다.

변경하고자 한다면 부모 컴포넌트에서 state를 변경시켜주어야 한다.

 

A 부모 컴포넌트 state = { A : "A" } 가 있다면

< B 컴포넌트 aProps = { this.state.a } /> 로 넘겨받을 수 있다.

<ChatMessages
	messages = {messages}
	currentMember={member}
/>

 

 


 

구조분해할당

배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 js 표현식

 

예시를 확인하면서 이해해보자

먼저 userProfile 이라는 객체를 만들어 보았다. 이름 나이 이메일 주소, 주소라는 객체가 또 있고 배열인 취미도 존재한다.

우린 이 객체의 속성을 해체해서 개별로 사용하고 싶다.

const userProfile = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30,
  email: 'john.doe@example.com',
  address: {
    street: '123 Main St',
    city: 'Anytown',
    zipCode: '12345'
  },
  hobbies: ['reading', 'gaming', 'hiking']
};

 

// 기본 객체 구조 분해
const { firstName, lastName, age } = userProfile;
console.log(firstName, lastName, age); // 출력: John Doe 30

// 중첩 객체 구조 분해
const { address: { street, city, zipCode } } = userProfile;
console.log(street, city, zipCode); // 출력: 123 Main St Anytown 12345

// 새 변수 이름 설정
const { email: userEmail } = userProfile;
console.log(userEmail); // 출력: john.doe@example.com

// 기본값 설정
const { phone = '전화번호 없음' } = userProfile;
console.log(phone); // 출력: 전화번호 없음

 

그렇다면 구조를 분해해서 원하는 값만 변수로 따로 빼서 사용하면 된다.

기본값을 통해 존재하지 않을때 처리도 가능하다.

 

 

배열에 대해 더 알아보면

색상이 담긴 배열 객체가 존재하고, 우린 이를 인덱스나 값을 통해 활용하고 싶다면

const colors = ['red', 'green', 'blue', 'yellow', 'purple'];
// 배열의 첫 번째와 두 번째 요소를 구조 분해하여 변수에 할당
const [firstColor, secondColor] = colors;
console.log(firstColor, secondColor); // 출력: red green

// 세 번째 요소를 건너뛰고 네 번째 요소를 구조 분해
const [, , , fourthColor] = colors;
console.log(fourthColor); // 출력: yellow

// 'rest' 구문을 사용하여 나머지 모든 요소를 새 배열로 구조 분해
const [firstColor, ...otherColors] = colors;
console.log(otherColors); // 출력: ["green", "blue", "yellow", "purple"]

// 배열에서 특정 위치에 있는 요소를 구조 분해하여 변수에 할당하고,
// 해당 위치에 요소가 없을 경우 기본값을 제공
const [firstColor, secondColor, thirdColor, fourthColor, fifthColor, sixthColor = 'orange'] = colors;
console.log(sixthColor); // 출력: orange

 

,  , , / rest / 원하는 값 등을 활용해서 배열에서 값을 뽑아 변수에 할당할 수 있다.

 

객체가 조금더 깊게 되어있다면?

사람 정보, 직무로 나눠진 employess 란 객체가 있다. 이 같은 경우에도  가능하다.

const employees = [
  {
    personalInfo: {
      name: 'John Doe',
      address: {
        street: '123 Main St',
        city: 'Anytown'
      }
    },
    jobDetails: {
      department: 'Sales',
      position: 'Sales Manager'
    }
  },
  {
    personalInfo: {
      name: 'Jane Smith',
      address: {
        street: '456 Elm St',
        city: 'Othertown'
      }
    },
    jobDetails: {
      department: 'Marketing',
      position: 'Marketing Director'
    }
  }
];

 

for (const { personalInfo: { name: employeeName, address: { city: employeeCity } }, jobDetails: { position: employeePosition } } of employees) {
  console.log(`Name: ${employeeName}, City: ${employeeCity}, Position: ${employeePosition}`);
}

// 결과
// Name: John Doe, City: Anytown, Position: Sales Manager
// Name: Jane Smith, City: Othertown, Position: Marketing Director

 

  • 분해한 변수 명
  • personalInfo 내 name 속성의 employeeName.
  • personalInfo 내부에 중첩된 address 개체 내 city 속성의 employeeCity.
  • jobDetails 내 position 속성의 employeePosition.

간결한 방식으로 객체 내의 중첩된 속성에 액세스하기 위해 심층 구조 분해를 사용할 수 있는 방법이다.

 


728x90

'프론트엔드 > React' 카테고리의 다른 글

React - Redux  (1) 2024.02.07
React - TDD, Testing Library, Jest, expect, matcher  (1) 2024.02.06
React - Memoization  (0) 2024.02.02
React - 불변성 정리  (1) 2024.02.01
Comments