TypeError:未定義のプロパティ 'state'を読み取れません



Typeerror Cannot Read Propertystateof Undefined



問題の説明:
状態の値を取得すると、reactコンポーネントのメソッドでエラーが発生します:TypeError:未定義のプロパティ「state」を読み取れません

解決:
方法1(これをコンストラクターの関数にバインドします): this.funOne = this.funOne.bind(this)



import React , {Component} from 'react' class Home extends Component { constructor(props){ super(props) this.state = { one: 'one' } this.funOne = this.funOne.bind(this) // Mainly this line binds this to the function funOne } funOne () { alert(this.state.one) } render () { return ( funOne ) } } export default Home

方法2(矢印関数を使用): funOne =()=> {}

import React , {Component} from 'react' class Home extends Component { constructor(props){ super(props) this.state = { one: 'one' } } funOne = () => { alert(this.state.one) } render () { return ( funOne ) } } export default Home

方法3(これをバインドしながらこのメソッドをバインドする): onClick = {this.funOne.bind(this)}



import React , {Component} from 'react' class Home extends Component { constructor(props){ super(props) this.state = { one: 'one' } } funOne () { alert(this.state.one) } render () { return ( funOne ) } } export default Home