美文网首页
回调函数里面调用this.setState方法出现以下错误

回调函数里面调用this.setState方法出现以下错误

作者: fanlehai | 来源:发表于2018-12-13 00:30 被阅读83次

    简介:React中使用setState出现:TypeError: this.setState is not a function
    learn-anything | 2018年12月13日00:30:17


    【问题】:回调函数里面调用this.setState方法出现以下错误:
    TypeError: this.setState is not a function
    

    【解决方案】:在回调函数处使用bind,带入如下:
    constructor(props) {
        super(props);
        this.state = {
            name:1
        }
    }
    
    click(){
      let _name = this.state.name
      console.log('click before')
      this.setState({
          name:++_name
      },()=>{
          console.log('click 回调')
      })
      console.log('click behind')
    }
    
    render() {
        console.log('render')
        return (
          <div onClick={this.click.bind(this)}>
             {this.state.name}
          </div>
        )
    }
    
    

    参考链接:

    相关文章

      网友评论

          本文标题:回调函数里面调用this.setState方法出现以下错误

          本文链接:https://www.haomeiwen.com/subject/eowuhqtx.html