我想在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 (
<p>Test</p>
)
}
}
ReactDOM.render(<Test/>,test);
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
问题出在
this指向上解决方案有很多种,楼上提出的都是可行的,不过我习惯上用箭头函数:
用箭头函数来绑定 this。
this指向问题,可以用es6箭头函数或者bind
用箭头函数,可以自动绑定this
用
function(){}.bind(this)最古老的,用
that替换`this`