카테고리 없음

📖 리액트) state 활용 예시

changha. 2020. 8. 25. 13:11

state를 사용해서 plus, minus 버튼을 클릭하면 

동적으로 바뀌는 것을 알아보자

 

import React from 'react';

class App extends React.Component {
  state = {
    count: 0,

  };

  add = () => {
    console.log('plus');
  };

  minus = () => {
    console.log('minus');
  }
  render() {
    return (
    <div>
      <h1>The number is: {this.state.count}</h1>
      <button onClick={this.add}>Add</button>
      <button onClick={this.minus}>Minus</button>
    </div>
    )}
}
export default App;

 

여기까지 따라왔으면 Add와 Minus 버튼을 누를 때 console에 문구가 뜨는 것을 확인 할 수 있다

 

중요한 것은 JavaScript를 알아서 add() 함수에 this.state.count++ 또는 

this.state.count = this.state.count + 1과 같은 코드를 작성하면 안된다!

 

react에서는 state는 아주 특별한 객체이다

따라서 함부로 바꾸면 경고 메시지가 뜰 것이다!

 

원래 리액트는 state가 변경되면 render()는 감지하여 다시 실행해서 변경된 state를 화면에 출력한다. 

그렇지만 state를 임의로 바꿔버리면 render는 다시 실행하지 않는다

 

그러면 어떻게 해결해야 할까?

해결책은 setState()이다, 새로운 state를 인자로 넘겨 주는 것이다

그러면 render도 변경된 state를 감지하여 함수를 다시 실행하게 된다

 

 add = () => {
    this.setState(current => ({
      count: current.count + 1,
    }));
  };

  minus = () => {
    this.setState(current => ({
      count: current.count -1,
    }));
  }

이런 식으로 setState()함수의 인자로 함수를 전달하는 방식을 사용하면 된다~

 

응용하면 더하기, 빼기 뿐만아니라 다양한 계산요소를 추가할 수 있다

Add/Minus 버튼을 클릭하면 새로고침 하지않고 숫자가 증감한다