날이 덥다…
날이 더워도 공부는… 계속된다…..
꾸준히 하자….!
오늘은 useState로 상태를 만들거다.
버튼을 클릭할 때마다, title에 있는 숫자를 1씩 누적되게 바꿔줄 때 사용할 예정이다…!!




const Form = () => {
  const counterState = React.useState(1);
  const counter = counterState[0];
  const setCounter = counterState[1]; 

  function handleFormSubmit(event) {
    event.preventDefault();
    console.log("폼 전송됨");
    setCounter(counter + 1);
  }
  return (
    <form onSubmit={handleFormSubmit}>
      <input type="text" name="name" placeholder="영어 대사를 입력해주세요" />
      <button type="submit">생성</button>
    </form>
  )
};

useState를 이용하여 counterState라는 변수를 만들었다.
useState 안에는 두가지 인자가 있는데,
하나는 실제 저장할 데이터가 있고, 하나는 저장할 데이터를 변경시킬 함수가 들어있다.
사실 사용하는 용도는 변수와 똑같은데 굳이 변수가 아닌 useState를 쓰냐면,
데이터가 변경될 때 HTML을 새로고침 없이 자동으로 재렌더링되어 웹페이지가 스무스하게 동작되기 때문이라고 한다.
아무튼 setCounter 변수를 이용하여 값을 변화시키면, counter변수에 변화된 값이 저장된다.



하나씩 변수선언 하는 것이 귀찮다면 한번에 처리할 수도 있다.

const [counter, setCounter] = React.useState(1);

바로 이렇게…!!!
훨씬 간단해졌다!!!
이제 저걸 이용해서 title 태그 안의 숫자를 바꿔주려는데 문제점이 있다.

const app = (
  <div>
    <Title>1번째 고양이 가라사대</Title>
    <Form />
    <MainCard img="https://cataas.com/cat/60b73094e04e18001194a309/says/react" alt="고양이" />
    <Favorites />
  </div>
);

const here = document.querySelector('#app');
ReactDOM.render(app, here);

아까 만들어준 상태는 form 안에 만들었기 때문에, form 에서만 쓸 수 있다.
그런데 나는 title에도 그 상태를 써야하는 상황인 것이다…!!!
이럴때 사용하는 것이 바로 상태 끌어올리기이다.
상태를 끌어올려서, form이 아닌 그 위의 부모의 위치에서 사용한다면
form에서도 title에서도, 심지어 MainCard와 Favorites에서도 사용가능하다!



그런데 상태를 만들어서 사용을 하려면 app이 엘리먼트가 아닌 컴포넌트여야 한다.
그래서 컴포넌트로 바꿔줄 것이다~

const App = () => {
  return (
    <div>
      <Title>{counter}번째 고양이 가라사대</Title>
      <Form handleFormSubmit={handleFormSubmit} />
      <MainCard img="https://cataas.com/cat/60b73094e04e18001194a309/says/react" alt="고양이" />
      <Favorites />
    </div>
  );
}

const here = document.querySelector('#app');
ReactDOM.render(<App />, here);

이렇게 하면 된다.
그러나 한 번 더 상태를 끌어올려야 한다…!
바로 setCounter를 하는 부분은 아직 form에 있기때문이다 ㅋㅋ



const Form = ({ handleFormSubmit }) => {
  return (
    <form onSubmit={handleFormSubmit}>
      <input type="text" name="name" placeholder="영어 대사를 입력해주세요" />
      <button type="submit">생성</button>
    </form>
  )
};


const App = () => {
  const [counter, setCounter] = React.useState(1);
  function handleFormSubmit(event) {
    event.preventDefault();
    console.log("폼 전송됨");
    setCounter(counter + 1);
  }
  return (
    <div>
      <Title>{counter}번째 고양이 가라사대</Title>
      <Form handleFormSubmit={handleFormSubmit} />
      <MainCard img="https://cataas.com/cat/60b73094e04e18001194a309/says/react" alt="고양이" />
      <Favorites />
    </div>
  );
}

const here = document.querySelector('#app');
ReactDOM.render(<App />, here);

짜자잔….!!
전송버튼을 눌렀을 때, counter 변수의 값을 바꿔주는 handleFormSubmit 라는 함수를 끌어올렸다.
부모 컴포넌트에서 선언하고, 그것을 자식컴포넌트에서 사용할 땐 props로 넘겨주기만 하면 된다!
어떤 상태들을 끌어올려서 사용할지는 코드의 재사용성, 가독성 등을 고려해서 하면 될 것이다.
그 부분을 진지하게 고려하면서 코드를 설계하고 짤 수 있도록 해야겠당ㅎㅎ

태그:

카테고리:

업데이트: