React中设置setState?

我想在React中调用ajax设置DATA,可是setState时报错?为什么报错信息如下?我该如何修改?
代码打包之类的是好的?可以打印出TEST

index.bundle.js?__VERSION:91 Uncaught TypeError: Cannot read property 'setState' of null

at success (http://localhost:8000/js/index.bundle.js?__VERSION:91:26)
at ajaxSuccess (http://localhost:8000/js/index.bundle.js?__VERSION:1906:31)
at XMLHttpRequest.xhr.onreadystatechange (http://localhost:8000/js/index.bundle.js?__VERSION:2107:99)

var $ = require('./zepto');
var React=require('react');
var ReactDOM=require('react-dom');

var test=document.getElementById('test');

class Test extends React.Component{
    constructor(){
        super();
        this.state = {
            DATA: "",
        };
    }

    componentDidMount(){
        $.ajax({
            url:'https://dev-promotion.chelun.com/GuangzhouCarShow/index?id=1',
            type:'GET',
            success:function(res){
                this.setState({
                    DATA:res
                })
                console.log(res)
            }
        })
    }
    render(){
        return (
            <div>Test</div>
            )
    }
}
ReactDOM.render(<Test/>,test);
阅读 5.5k
5 个回答

问题出在this指向上

success函数中,this指向的是如下的配置对象,而不是Test类的实例
{
    url:'https://dev-promotion.chelun.com/GuangzhouCarShow/index?id=1',
    type:'GET',
    success:function(res){
        this.setState({
            DATA:res
        })
        console.log(res)
    }
}
当执行success这个回调函数的时候,该对象实际上是销毁了的,因此会报你上面列出来的`Cannot read property 'setState' of null`错误.

解决方案有很多种,楼上提出的都是可行的,不过我习惯上用箭头函数:

也就是把
success:function(res){
    this.setState({
        DATA:res
    })
    console.log(res)
}
替换成
success: (res) => {
    this.setState({
        DATA:res
    })
    console.log(res)
}    
$.ajax({
            url:'https://dev-promotion.chelun.com/GuangzhouCarShow/index?id=1',
            type:'GET',
            success:function(res){
                this.setState({
                    DATA:res
                })
                console.log(res)
            }
        }.bind(this));

用箭头函数来绑定 this。

success: (res) => {
  this.setState({
    DATA:res
  })
  console.log(res)
}

this指向问题,可以用es6箭头函数或者bind

success: (res)=> {
    this.setState({
        DATA:res
    })
}
  1. 用箭头函数,可以自动绑定this

  2. function(){}.bind(this)

  3. 最古老的,用that替换`this`

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题