ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • state
    개발/react 2020. 12. 11. 18:00

    state는 리액트 컴포넌트 내에서 사용할 변수를 관리하는 역할을 한다. 예로 간단하게 정수 값을 표시하고 1씩 증가시키고 감소시키는 버튼이 있다고 하자. 아래와 같은 기능을 제공하는 앱이라면 컴포넌트중 누군가는 현재 화면에 표시되는 값을 들고 있어야 한다.

     

    1. state 관리

     

    이 값은 컴포넌트내의 state 변수에서 관리한다. 아래 코드를 보면 App 컴포넌트의 생성자에서 state를 만들고 그 안에 counter라는 값을 초기화 하는 것을 볼 수 있다. 그리고 render() 함수에서 현재 state 값을 참조해 counter 값을 보여주고 있다.

     

    class App extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                counter: 0
            };
        }
    
        render() {
            const title = '아는개발자'
            const subtitle = '이번에는 state를 공부해봅시다'
            const incrButton = '+1'
            const decrButton = '-1'
            return (
                <div>
                    <Header title={title} subtitle={subtitle} />
                    <Action buttonName={incrButton} />
                    <Action buttonName={decrButton} />
                    <p>현재 값: {this.state.counter}</p>
                </div>
            )
        }
    }

     

    2. state 변경 

     

    state 값을 업데이트 할 때는 constructor 함수에서 처럼 this.state 값에 직접 업데이트 하는게 아니라 setState 함수를 사용한다. state 값이 업데이트 되면서 이 값을 참조하고 있는 ui도 동적으로 업데이트하기 위해서다. 이렇게 하지 않으면 state 값만 바뀌고 실제 화면은 그대로 남게된다. 

     

    class App extends React.Component {
        constructor(props) {
            super(props);
            this.handleIncrease = this.handleIncrease.bind(this)
            this.handleDecrease = this.handleDecrease.bind(this)
            this.state = {
                counter: 0
            };
        }
    
        handleIncrease() {
            this.setState((prevState) => ({
                counter: prevState.counter + 1
            }))
        }
        handleDecrease() {
            this.setState((prevState) => {return {counter: prevState.counter - 1}})
        }
    
        render() {
            ...
            const incrButton = '+1'
            const decrButton = '-1'
            return (
                <div>
                    ...
                    <Action buttonName={incrButton} handleClick={this.handleIncrease} />
                    <Action buttonName={decrButton} handleClick={this.handleDecrease} />
                    <p>현재 값: {this.state.counter}</p>
                </div>
            )
        }

     

    handleIncrease 함수와 handleDecrease 함수에서 setState 내부 구현부를 살짝 다르게 했다. handleIncrease처럼 간단하게 값을 업데이트할 수도 있고 handleDecrease처럼 return까지 포함해서 값을 업데이트 할 수도 있다.

     

    3. 소스코드

    https://github.com/kwony/react-study/blob/main/src/playground/blog-state.js

     

    '개발 > react' 카테고리의 다른 글

    webpack  (0) 2020.12.13
    localStorage  (0) 2020.12.11
    Props  (0) 2020.12.11
    babel  (0) 2020.12.06
    arrow function  (0) 2020.12.06

    댓글

Designed by Tistory.