본문 바로가기

프론트엔드관련 책예제실습정리/리기술요약

컴포넌트2 -state

5.state

state와 props의 차이 :

state는 컴포넌트 내부에서 바뀔수 있는 값, props는 컴포넌트 사용과정에서 부모컴포넌트에서 설정하는값(읽기전용)

5-1.클래스형 컴포넌트 setState 사용

-constructor 의 this.state로 초깃값설정 > constructor 제거하고 초깃값 설정도 가능

-this.setState에 객체 대신 함수인자 전달하기, 함수에서 바로 객체 반환하기

-this.setState 함수 이후 콜백함수부르기(setSTate의 두번쨰 파라미터에 callback함수 등록)

///////////////App.js
import React from "react";
import Counter from "./Counter";

const App = () => {
  return <Counter />;
};

export default App;


//////////////////Counter.js
import React, { Component } from "react";

class Counter extends Component {
  // constructor(props){
  ////***super(props) 를 호출하는 것은 생성자 내부에서도 this.props 를 정상적으로 사용 가능하게함
  //   super(props)
  //   this.state{
  //     number: 0,
  //     fixedNumber: 0,
  //   }
  // }
  state = {
    number: 0,
    fixedNumber: 0,
  };
  render() {
    const { number, fixedNumber } = this.state;
    return (
      <div>
        <h1>{number}</h1>
        <h2>변하지 않는 값:{fixedNumber}</h2>
        <button
          onClick={() => {
            this.setState((prevState) => {
              return {
                number: prevState.number + 1,
              };
            }); //함수를 인자로
            //위 내용과 동일 but, 함수에서 바로 객체를 반환함 (return값x)
            this.setState(
              (prevState) => ({
                number: prevState.number + 1,
              }),
              () => {
                console.log("complete");
              }//this.setState가 끝난후 특정작업실행
            );
          }} //onClick
        >
          +1
        </button>
      </div>
    );
  }
}

export default Counter;

5-2.함수형 컴포넌트에서 useState 사용

배열 비구조화할당문법 사용 

const array = [1 , 2];

const [one, two] = array

//App.js
import React from "react";
import Say from "./Say";

const App = () => {
  return <Say />;
};

export default App;


//Say.js
import React, { useState } from "react";

const Say = () => {
  const [message, setMessage] = useState("");
  const onClickEnter = () => setMessage("안녕하세요");
  const onClickLeave = () => setMessage("안녕히가세요");
  const [color, setColor] = useState("black");
  return (
    <div>
      <button onClick={onClickEnter}>입장</button>
      <button onClick={onClickLeave}>퇴장</button>
      <h1 style={{ color }}>{message}</h1>
      <button style={{ color: "red" }} onClick={() => setColor("red")}>
        빨강
      </button>
      <button style={{ color: "blue" }} onClick={() => setColor("blue")}>
        파랑
      </button>
      <button style={{ color: "green" }} onClick={() => setColor("green")}>
        초록
      </button>
    </div>
  );
};
export default Say;

5-3.state 사용시 주의사항

:배열이나 객체를 업데이트 할때는 바드시 사본에 값을 업데이트한후 사본에 state 사용

//배열이나 객체를 업데이트 할때는 바드시 사본에 값을 업데이트한후 사본에 state 사용

//객체다루기
const object = {a:1,b:2,c:3},
const nexObject = {...object,d:4};

//배열다루기
const array = [
{id:1,value:true},
{id:2,vaule:true},
{id:3,value:false}];

let nextArray = array.concat({id:4}); //새항목 추가
nextArray.filter(item=>item.id !==2) ; //id가 2인 항목 제거
nextArray.map(item =>item.id ===1? {...item,value:false}:item)); // id가 1인 항목의 value를 false로 설정

'프론트엔드관련 책예제실습정리 > 리기술요약' 카테고리의 다른 글

ref:DOM에 이름달기  (0) 2021.06.11
이벤트핸들링2  (0) 2021.06.04
이벤트핸들링1  (0) 2021.06.04
컴포넌트 1 -component,import, props(prototype)  (0) 2021.06.02
JSX 문법 정리  (0) 2021.06.02