reactjs 在点击分页的时候,改变 state 报错
TypeError: _this2.setState is not a function(…)
下面是 代码
GetApiData(index){
let pageid = index;
let gitusername = this.state.gitusername;
let gitreponame = this.state.gitreponame;
let endApiUrl = '/api/getissues?gitusername='+ gitusername +'&gitreponame='+ gitreponame +'&pageid='+pageid;
fetch(endApiUrl)
.then((response) => {
return response.json();
})
.then((obj) => {
// 只要有以下这句话就会报错 走 `catch`
this.setState({
data: obj
});
})
.catch((ex) => {
console.log(ex);
});
}
onChange(index){
this.setState = {
pageid:index,
}
this.GetApiData(index);
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
ajax请求的回调中的this并不指向react组件对象,所以找不到setState方法。
我将楼主你的代码复制下来,我会在改动的地方用注释标注出来。
原因上面的 @cxxsn 已经提出来了,这个时候的
this的指向不是你写的这个component,他的办法是使用var _this = this;,还有一种是我采用的方法,那就是给回调函数.bind(this)。这样的用法我记得好像是在官方文档里还是materia-ui中看到的示例代码。我比较常用的方法是这个`GetApiData(index){