미미 공부/취미방

[노마드 코더] All you need to know about State #3.1 본문

Programming

[노마드 코더] All you need to know about State #3.1

mionager 2021. 10. 20. 22:41

https://nomadcoders .co/courses

1) setState()로 state object 변화를 감지하고 render를 다시 동작시켜야 된다.

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

  add = () => {
    console.log("add");
  };
  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>
    )
  }
}
  add = () => {
    this.state.count = 1;
  };
  minus = () => {
    this.state.count = -1;
  };

위의 코드는 동작하지 않는다.

그 이유는 

add / minus 버튼을 클릭 > state object의 값이 변함 > 변한 값을 감지 > render 하위 요소들을 다시 읽어줘야 하는데,

변화감지 / render 다시 읽어주기를 못 한다.

 

setState()는 이런걸 동작하기 때문에, 데이터가 변할때는 반드시 setState()를 사용해야 된다.

2) setState를 사용한 코드

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

remove = () => {
	this.setState({count : this.state.count - 1});
}

하지만, setState안에 this.state가 들어가는게 좋지 않아서 코드를

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

remove = () => {
	this.setState(someProp => ({count : someProp.count - 1}));
}

저 arrow function과 this.state가 someProp으로 대체될 수 있는건 공부를 더 하고 와야겠다...

(ES6랑 연관이 있는것 같음)

Comments