State

손영훈·2023년 7월 1일

React

목록 보기
4/8
post-thumbnail

State란?

  • Prop과 함께 컴포넌트 함수를 다시 실행해서 새로운 return값을 만들어주는 하나의 데이터
  • Prop과 State 모두 값이 변경되면 새로운 return값을 만들어 UI를 바꾼다.

Prop과 State의 차이점

  • Prop은 컴포넌트를 사용하는 외부자를 위한 데이터
  • State는 컴포넌트를 만드는 내부자를 위한 데이터

State사용법

mode의 값이 무엇이냐에 따라 본문의 내용이 달라지도록!

import하기

import {useState} from 'react';
  • useState라는 Hook을 사용(react에서 제공하는 기본적 함수)
function App() {
  const mode = 'WELCOME';
  const topics = [
    {id:1, title:'html', body:'html is...'},
    {id:2, title:'css', body:'css is...'},
    {id:3, title:'javascript', body:'javascript is...'},
  ]
  
  let content = null;
  if(mode === 'WELCOME'){ // mode의 값이 welcome이라면 
    content = <Article title="Welcome" body="Hello, WEB"></Article>
  }else if(mode === 'READ'){ //mode의 값이 read라면
    let title, body = null;
    for(let i=0; i<topics.length; i++){
      console.log(topics[i].id, id)
      if(topics[i].id === id){
        title = topics[i].title;
        body = topics[i].body;
      }
    }
    content = <Article title={title} body={body}></Article>
  }
  return (
    <div>
      <Header title="WEB" onChangeMode={()=>{
        mode = 'WELCOME';
      }}></Header>
      <Nav topics={topics} onChangeMode={(_id)=>{
        mode = 'READ';
        setId(_id);
      }}></Nav>
      {content} //변수 content 출력!
    </div>
  );
}
  • mode의 값이 이벤트가 발생했을 때 변경하기
  • 상수 mode를 state로 업그레이드하기
const _mode = useState('WELCOME');
console.log('_mode', _mode);

콘솔로 확인!

  • _mode의 0번째 값은 "WELCOME"과 같다. (상태의 값을 읽을 때 사용)
  • 1번째 값은 함수 (상태의 값을 변경할 때 사용하는 함수)
const _mode = useState('WELCOME');
const mode = _mode[0];
const setMode = _mode[1];
console.log('_mode', _mode);
  • 따라서 const mode= _mode[0];은 mode의 값을 통해 상태의 값을 읽을 수 있다.
  • const setMode = _mode[1];은 setMode를 통해 mode의 1번째 값 함수를 변경할 수 있다.
const [mode,setMode] = useState('WELCOME'); //축약 코드
	<div>
      <Header title="WEB" onChangeMode={()=>{
        setMode('WELCOME');
      }}></Header>
      <Nav topics={topics} onChangeMode={(_id)=>{
        setMode('READ');
        setId(_id);
      }}></Nav>
      {content} //변수 content 출력!
    </div>
  • 값을 바꾸기 위해 setMode사용
  • 실행을 해보면 mode의 값이 setMode로 인해 READ로 바뀐다.
  • App 컴포넌트가 다시 실행됨
  • useState가 mode의 값을 READ로 세팅
  • if문을 통해 해당 id값을 렌더링한다.
profile
메모장

0개의 댓글