this.setState is undefined

前端 未结 8 2112
无人及你
无人及你 2020-12-09 01:24

I keep seeing answers that say to use => or .bind(this) but neither of those solutions worked.

import React, { Component } from \'react\';
import { View, Tex         


        
8条回答
  •  没有蜡笔的小新
    2020-12-09 02:14

    you need to bind your action otherwise you can see error called undefined in your browser there are three methods for binding your action

    1. bind the handler in the render method this.chngHandler.bind(this)

    for eg-

    export class EventBind extends Component{
    constructor(){
        super()
        this.state = {
            msg:'hello'
        }
    }
    chngHandler(){
        this.setState({
             msg:'Good bye'
        })
    }
    render(){
        return(
            
    {this.state}
    ) } }
    1. arrow function approach in render ()=>this.EventHandler()

    for example-

    export class EventBind extends Component{
    constructor(){
        super()
        this.state = {
            msg:'hello'
        }
    }
    chngHandler(){
        this.setState({
             msg:'Good bye'
        })
    }
    render(){
        return(
            
    {this.state}
    ) }}`

    3.Binding the event handler in the constructor this.EventHandler = this.EventHandler.bind(this) for example-:

    export class EventBind extends Component{
    constructor(){
        super()
        this.state = {
            msg:'hello'
        }
        this.chngHandler = this.chngHandler.bind(this)
    }
    chngHandler(){
        this.setState({
             msg:'Good bye'
        })
    }
    render(){
        return(
            
    {this.state}
    ) }}

    because the binding happens once in the constructor this is better than a binding in the render method

    3rd approach can also be done like this -:

    export class EventBind extends Component{
    constructor(){
        super()
        this.state = {
            msg:'hello'
        }
        this.chngHandler = this.chngHandler.bind(this)
    }
    // chngHandler(){
    //     this.setState({
    //          msg:'Good bye'
    //     })
    // }
    chngHandler = ()=>{
        this.setState({
            msg:'Good Bye'
        })
    }
    render(){
        return(
            
    {this.state}
    ) }}

提交回复
热议问题