3.3 state

hey hey·2021년 12월 9일
0

리액트 배우기

목록 보기
5/26
post-thumbnail

state

컴포넌트 내부에서 지닌값, 바뀔 수 있는 값을 의미

  • props는 컴포넌트가 사용되는 과정에서 부모 컴포넌트가 설정하는 값 props를 바꾸려면 부모 컴포넌트에서 바꿔야 한다.

클래스형 컴포넌트의 state

import React,{Component} from "react";

class Counter extends Component{
  constructor(props){
    super(props);
    this.state={
      number:0,
    }
  }
  render(){
    const {number}=this.state
    return (
      <div>
        <h1>{number}</h1>
        <button 
          onClick={()=>{this.setState({number:number+1})
        }}
        >+1</button>
      </div>
    )
  }
}
export default Counter

constructor

  • 컴포넌트에 state를 설정할 때 사용
  • 반드시 super(props) 호출해야 한다.
    • 현재 클래스형 컴포넌트가 상속받고 있는 리액트의 Component 클래스가 지닌 생성자 함수를 호출해 준다.
  • this.state 값에 초깃값 설정

render( ) 안

  • const {number}=this.state
    • state 조회할 때는 this.state로 조회한다.
  • onClick={()=>{this.setState({number:number+1})}
    • 이벤트 설정에 함수를 넣을 때는 화살표 함수로
    • setState로 state값 변경

state에 여러값이 존재할 때

  • setState는 인자로 전달된 객체 안에 들어 있는 값만 바꾼다.
  • 다른 값 신경 안써도 된다.

constructor 없이 사용

class Counter extends Component{  
  state={
    number:0,
    fixedNumber:0,
  } 
  render(){..}}

뭐야.. 간단하네..

this.setState에 함수 전달하기

this.setState((prevState,props) ⇒{return{ }})

prevState : 기존상태 props : 현재 지니고 있는 props (생략가능)

<button 
	onClick={()=>{
	  this.setState(prevState =>{
	    return {
	      number:prevState.number + 1}})
	  
	  this.setState(prevState =>{
	    return {
	      number:prevState.number + 1}})
}}
>+1
</button>

useState [권장]

const array = [1,2]

const [a,b] = arraya = array[0], b = array[1]

import React,{useState} from "react";

const Say = () =>{
  const[message,setMessage] = useState('');
  const onClickEnter = () => setMessage('어서오세요')
  const onClickLeave = () => setMessage('안녕히가세요')
  return(
    <div>
      <button onClick={onClickEnter}>입장</button>
      <button onClick={onClickLeave}>퇴장</button>
      <h1>{message}</h1>
    </div>
  )

}
export default Say;

useState 함수의 인자에는 상태의 초기값을 넣어준다.

const[message,setMessage] = useState('');

첫번째 원소는 현재 상태,

두번째는 상태를 바꿔주는 setter 함수

버튼으로 글자색 바꿔보기

const[color,setColor] = useState('black')
<h1 style={{color}}>{message}</h1>
<button style={{color:'red'}} 
    onClick={()=>{setColor("red")}}>
    빨간색
</button>

주의사항

state 값을 바꿀 때는 setState or useState를 통해 바꿔야한다.

object 형태를 업데이트 할때는 어떻게 해야하나?

const object ={a:1,b:2,c:3}
const ObjectCopy = { ...object,b:2};

spread 연산자( ... )

{ ...object,b:2}; 사본 만들기

새항목 추가

= concat

const array =[
	{id:1,value:true},
	{id:2,value:false},
	{id:3,value:true}]
let nextArray = array.concat({id:4});

항목 제거

nextArray.filter(item=> item.id !== 2);

= id 가 2가 아닌 것만 남긴다 → 2를 제거한다.

nextArray.map(item=> (item.id===1 ? {...item, value:false} : item))

= id 가 1이면 ? item값의 value 를 바꿔준다.

1이 아니면? 원래 item 그대로 가져온다

profile
FE - devp

0개의 댓글