이벤트에서 state 변경

SPANKEEE·2022년 11월 22일
0

리액트-시작

목록 보기
14/30

클릭시 mode 변경해보기

이전에 헤딩태그 안에 있는 <a>를 클릭할때 <App>컴포넌트 안의 mode값을 welcome으로 바꾸려 했었다.

<App> <heaer>내부 --> <Subject>컴포넌트 주석

<header>
  <h1>
    <a href='/' onClick={function (e) {
      console.log(e); // 이벤트 매개변수 e 출력
      e.preventDefault(); // a 태그의 동작을 금지함
      // state mode 변경
      this.state.mode = 'welcome';
    }}>{this.state.subject.title}
    </a>
  </h1>
  {this.state.subject.sub}
</header>

결과

위와 같이 오류가 뜬다.

이유가 뭘까?

첫번째로 이벤트가 호출될 때 실행되는 함수 안에서 "this"의 값이 컴포넌트 자기자신을 가르키지 않고 아무 값도 세팅되어 있지 않기 때문이다.

즉, "undefined"state를 읽으려고 했기 때문에 값을 알 수 없다는 오류가 발생하게 된 것이다.

bind()

event를 설치할 때 "this"의 값을 찾을 수 없어서 에러가 발행하면 함수가 끝난 직후에 bind(this)를 추가하면 된다.
bind(this)를 추가하면 함수 안에서 "this"는 컴포넌트 자신을 가르키게 된다.

<App> <heaer>내부 --> <Subject>컴포넌트 주석

<header>
  <h1>
    <a href='/' onClick={function (e) {
      console.log(e); // 이벤트 매개변수 e 출력
      e.preventDefault(); // a 태그의 동작을 금지함
      // state mode 변경
      this.state.mode = 'welcome';
    }.bind(this)}>{this.state.subject.title}
    </a>
  </h1>
  {this.state.subject.sub}
</header>

하지만 오류가 발생한다.

위 코드로 수정해도 왜 작동되지 않는걸까?

this.setState({})

두번째 이유는 리액트는 state의 값이 바뀐 사실을 모르기 때문이다.

이번엔 리랙트 사용설명서 방식으로 this.setState()함수를 호출할 때 mode를 welcome으로 바꾸도록 수정해 보자

<App> <heaer>내부 --> <Subject>컴포넌트 주석

<header>
  <h1>
    <a href='/' onClick={function (e) {
      console.log(e); // 이벤트 매개변수 e 출력
      e.preventDefault(); // a 태그의 동작을 금지함
      // state mode 변경
      this.setState({
        mode: 'welcome'
      });
    }.bind(this)}>{this.state.subject.title}
    </a>
  </h1>
  {this.state.subject.sub}
</header>

결과

state안에 있는 welcome의 속성 출력을 확인할 수 있다.

다음챕터에 어떤 과정을 거치는지 알아보자

profile
해야되요

0개의 댓글