react中报错Cannot read property 'setState' of undefined ,react模块的函数中获取不到this

Cannot read property 'setState' of undefined 一般这种报错会出在这样的语句中this.setState({name:value});

因为this是undefined,所有没有setState()函数(可以自己console.log(this)是不是undefined);

下面是源码,作为参照:(在index.jsx文件中)

class A extends React.Component{

    constructor(){    

        super();    //这句也很重要,这样才能在里面继承this

        this.sate = {  name: "hello world"};

        //this.click  = this.click.bind(this);  //这句是关键,没有加就会如上的错误,自己可以尝试下

   }

    click(){

    this.setState(name:"hello money")

     }

     render(){

      return  

this.click()}/>{this.state.name}

    }

}

class B extends React.Component{

     render(){

        return

点击我呀

     }

}


所以关键就是在constructor中有super();this.click = this.click.bind(this);  




你可能感兴趣的:(react中报错Cannot read property 'setState' of undefined ,react模块的函数中获取不到this)