[React] Cannot read properties of undefined (reading 'setState')

나의 기술 블로그·2024년 8월 5일

에러처리

목록 보기
7/11

문제 발생

리액트 과제를 하던 중, this.setState 를 사용하니, 밑의 에러가 발생하였다.

Cannot read properties of undefined (reading 'setState')

기존의 나의 코드는 클래스형 컴포넌트를 생성한 뒤, 버튼을 클릭하면 btnClick 함수가 실행되면서 값을 바꾸는 것이다.

import React, { Component } from 'react'

export default class HandlerEx extends Component {
    state = {
        count : 'Hello World',
    };
    btnClick() {
        console.log("btn Click");
        this.setState({count :'Goodbye World! '});
    }
        
    render() {
        const {count} = this.state;
        return (
            <>
            <h1>{count}</h1>
            <button onClick={this.btnClick}>Click!</button>
            </>
        )
    }
}

원인

호출하는 함수가 bind되지 않아서 그렇다.

해결방법


방법1 - 생성자에서 바인딩 해주기

this.btnClick = this.btnClick.bind(this);

방법2 - 화살표 함수로 구현

...
btnClick = (props) =>{
        console.log("btn Click");
        this.setState({count :'Goodbye World! '});
    }
...

리액트를 배운지 이틀 차인데, 함수 선언부분 방식에 따라 에러 내역이 바뀌다니!

아직은 처음이라 기본 문법을 제대로 이해하진 못했지만, 앞으로 화살표 함수로만 써야겠다.

profile
문제해결을 두려워하지 말자!

0개의 댓글