ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Cannot read properties of undefined this
    React 2023. 1. 9. 16:03

    始めに

    ReactのClassComponentの中で、stateをalertする関数を作成し、文字をクリックするとその関数が 呼ばれるようにしたら、以下のエラーが発生。

    Uncaught TypeError: Cannot read properties of undefined (reading 'state')

    コード

    import React, { Component } from 'react'
    
    export default class ClassComponent extends Component {
    
        constructor(props) {
            super(props);
            this.state = { date : new Date() };
        }
    
        handleClick() {
            alert(this.state.date);
        }
    
        render() {
            return (
                <div>
                    <h1 onClick={this.handleClick}>Hello, world!</h1>
                    <div>{this.state.date.toLocaleTimeString()}</div>
                </div>
            )
        }
    }
    

    原因と対策

    handleClick()は、classComponentのライフサイクルに定義されていない外部の関数であるため、
    参照のエラーが発生しました。
    そのため、問題の関数とclassComponentをお互いにbindしてあげなければなりません。
    classComponentは自分自身をhandleClickに知らせるため!
    もし、外部の関数からclassComponetの値に参照しない場合は不要

    classComponent lifeCycle

    修正後コード

    import React, { Component } from 'react'
    
    export default class ClassComponent extends Component {
    
        constructor(props) {
            super(props);
            this.state = { date : new Date() };
            this.handleClick = this.handleClick.bind(this); //追加したコード、thisと外部の結合
        }
    
        handleClick() {
            alert(this.state.date);
        }
    
        render() {
            return (
                <div>
                    <h1 onClick={this.handleClick}>Hello, world!</h1>
                    <div>{this.state.date.toLocaleTimeString()}</div>
                </div>
            )
        }
    }
    

    他の案

        handleClick = () => {
            alert(this.state.date);
        }
    

    arrow functionにすることで、thisが誰なのかがわかるため、bindコードを省略することが可能になる。

    'React' 카테고리의 다른 글

    Virtual Dom vs Real Dom  (0) 2023.01.15
    syntheticEvent  (0) 2023.01.10
    State  (0) 2023.01.08
    props③ - Extractions  (0) 2023.01.08
    JSX  (0) 2023.01.06

    댓글

Designed by Tistory.