0
0

More than 1 year has passed since last update.

外部の関数からthisを参照しようとしたら、エラー。

Posted at

始めに

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コードを省略することが可能になる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0