ReactJS로 영화 웹 서비스 만들기 : Chapter 3

잉퓨·2023년 5월 5일
post-thumbnail

Understanding State

<!DOCTYPE html>
<html lang="en">
  <body>
    <div id="root"></div>
  </body>
  <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  <script type="text/babel">
    const root = document.getElementById("root");

    const container = (
      <div>
        <h3>Total clicks: 0</h3>
        <button>Click me</button>
      </div>
    );
    ReactDOM.render(container, root);
  </script>
</html>

⇒ 기존의 코드를 다음과 같이 수정하였다.

  • React Element를 만들고 있는 Container가 존재한다.
    • ht와 button이라는 2개의 React Element를 만들고 있다.
let counter = 0;
const container = (
      <div>
        <h3>Total clicks: {counter}</h3>
);

⇒ 변수를 받아올 필요 없이 중괄호 안에 counter를 넣으면 변수를 넣을 수 있다.

function countUp(){
        counter = counter + 1;
    }

count의 값을 1씩 증가시켜주는 함수를 만들었다.

Trouble : UI count값이 증가하지 않는 문제

클릭할 때 마다 console의 counter 값은 증가하나, 실질적인 화면 내의 count 값은 증가하지 않는다.

ReactDOM.render(container, root);

Container를 한번만 렌더링 할뿐, 클릭될때 새로 위의 구문을 불러와주는 과정이 필요하다.

⇒ countUp function에 render 함수를 추가해주어야 한다.

function countUp(){
        counter = counter + 1;
        ReactDOM.render(<Container />, root);
    }

다음과 같이 countUp에 Container render를 추가하여 계속해서 countUp 될때마다 렌더링이 되도록 한다.

React는 Btn, H3 등의 태그를 다시 로딩할 필요 없이, 바뀐 부분만 업데이트 하면 된다는 이점이 존재한다.

setState

const root = document.getElementById("root");
    function App() {
      const data = React.useState(0);
      return (
      <div>
        <h3>Total clicks: 0</h3>
        <button>Click me</button>
      </div>
      );
    }
    ReactDOM.render(<App />, root);

⇒ React.useState를 사용하는 형식으로 바꾸게 된다

  • data → undefined(⇒ 0으로 설정시 0)와 f라는 함수를 얻고 있다.
    • f → data를 바꿀때 사용되는 함수

즉, 기존의 countUp에서 사용하는 f와, counter=0;의 역할을 했던 내용을 한번에 하는 것으로 생각할 수 있다.

Untitled

⇒ 다음과 같은 방식으로 각각의 변수에 배열의 내용을 할당하는 것이 가능하다. 본 내용을 적용해보고자 한다.

const root = document.getElementById("root");
    function App() {
      const [counter, setCounter] = React.useState(0);
      const onClick = () => {
        setCounter(counter+1);
      }

modifier → setCounter 함수의 사용을 통해 자동으로 Render가 됨과 동시에 업데이트가 가능하게끔 한다.

State Functions

const onClick = () => {
        //setCounter(counter+1);
        setCounter((current) => current +1);
      };
  • SetCounter를 counter 값을 받게될 시, 다른 곳에서 변경되었을 경우 잘못된 값이 불러와질 수 있다.

⇒ 따라서, 위의 방식을 활용하여 current 값을 받아오고, 해당 값에 +1을 하는 방식으로 수정되면 안전한 작성이 가능하다.

Inputs and State

<div>
        <h3>Super Converter</h3>
        <label for = "minutes">Minutes</label>
        <input id = "minutes" placeholder="Minutes" type ="number"/>
        <label for = "hours">Hours</label>
        <input if = "hours" placeholder="Hours" type ="number"/>
</div>
  • input 위에 label을 넣어 둘 사이를 연결해주게 된다
    • 직접적인 연결을 위해 for과 id를 사용하여 연결한다

Trouble

  • for과 같은 용어를 사용할 수 없다 → JS의 용어이므로, class, for과 같은 용어를 사용해주면 오류가 발생하게 된다.

⇒ htmlFor등으로 변경 시 오류가 발생하지 않는다.

function App() {
      const [minutes, setMinutes] = React.useState()
      const onChange = () => {};
      return (
      <div>
        <h3 className= "hi">Super Converter</h3>
        <label htmlFor = "minutes">Minutes</label>
        <input 
          value={minutes} 
          id = "minutes" 
          placeholder="Minutes" 
          type ="number"
          onChange = {onChange}
        />
        <label htmlFor = "hours">Hours</label>
        <input if = "hours" placeholder="Hours" type ="number"/>
      </div>
      );
  • 위와 같이 사용하게 되면, input의 값이 onChange(변화가 생길 때 마다) onchange 함수를 수행할 수 있다.
const onChange = () => {
        setMinutes(event.target.value)
      };

다음과 같이 변경 시마다 minutes 값을 불러오는 event.target.value를 통해 새로 minute 값을 셋팅하고, render가 되도록 setMinutes 함수를 사용한다.

State Practice

<input
            value ={Math.round(minutes/60)}
            id = "hours" 
            placeholder="Hours" 
            type ="number"
            disabled={false}
          />
  • input의 내용에 disabled를 true로 하게 되면, 입력 칸에 입력을 할 수 없다, 하지만 false로 하면 입력을 할 수 있다.

⇒ 해당 항목을 통해서 입력의 유무를 컨트롤 할 수 있다.

Reference

profile
블로그 이전했습니다(https://security-inpyu.tistory.com/)

0개의 댓글