我想在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);
问题出在
this
指向上解决方案有很多种,楼上提出的都是可行的,不过我习惯上用箭头函数: