一般出现这种问题的时候有两种很简便的方法解决:
1、手动绑定this,直接在constructor()里面加入
this.函数名 = this.函数名.bind(this);//手动绑定
2、将原来的那个函数改为箭头函数
还有一种就是下面这种特殊情况↓。
get(){
let data = {
offset:0,
length:10
}
app.post('products/get',data,function(res){
console.log(res)
this.setState({
})
})
}
这种情况用了上面那两个方法也还是会报错,原因就是因为在一开始的constructor()里面已经有了this.state={}了
解决方法:
get(){
let data = {
offset:0,
length:10
}
let me = this
app.post('products/get',data,function(res){
console.log(res)
me.setState({
})
})
}