TIL] React-state

5206 단어 ReactStateTILReact

🐱 State

state는 render 함수가 실행되는 조건으로 component의 state는 props와 다르게 외부로 전달되지 않고 자신만의 고유한 state를 갖는다.
⁎ class 안에 state를 추가할 때는 render()와 구분하기 위한 ,를 사용하면 안된다. class는 객체가 아니기 때문이다.

  • Class component에 state 추가하기
    ⁎ super(props); 선언전에는 this. syntax를 사용할 수 없다.

  • State에 접근하기

    . this.state.name-of-property

🐭 Update state(this.setState)

state는 자신의 state를 읽는 것 뿐만 아니라 스스로 state를 변화시킬 수도 있다. state를 바꿀 때는 this.setState() 함수를 호출해야 한다. 이 함수는 2개의 argument를 취하는데, 첫번째는 update가 필요한 component의 state와 callback(optional)이다. setState()가 호출될 때 자동으로 render 함수가 실행되며 해당 시점에 상태가 변화하지 않은 property는 기존의 상태를 유지하고 변경된 부분만 반영된다.
⁎ render 함수 안에 state가 있으면 해당 class는 무한 loop가 될 것이다. 😓

{
  mood:   'great',
  hungry: false
}

this.setState({ hungry: true });


{
  mood:   'great',  //mood는 변하지 않음
  hungry: true
}
  • Call this.setState from another function

    . this.setState()를 호출하는 가장 보편적인 방법은 setState()가 작성된 사용자 지정 함수를 호출하는 것이다.

 class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { weather: 'sunny' };
    this.makeSomeFog = this.makeSomeFog.bind(this);
  }

  makeSomeFog() {    //custom function
    this.setState({
      weather: 'foggy'
    });
  }
}

    . 사용자 지정 함수를 호출할 때 주의해야 할 점이 있다. 바로 JavaScript가 eventHandler를 binding하는 방식으로 인해서 attribute에 할당된 handler의 this가 유효하지 않게 된다는 점이다.
eventHandler를 this를 사용하여 정의할 경우, constructor에 this.methodName = this.methodName.bind(this)를 꼭 추가하여 해당 method가 현재 obj를 가리키는 것이라고 알려줘야 한다.

좋은 웹페이지 즐겨찾기