gpt4 book ai didi

reactjs - 使用superagent和React从API响应中获取setState

转载 作者:行者123 更新时间:2023-12-04 19:59:02 25 4
gpt4 key购买 nike

尝试更改组件状态时收到错误消息。


未捕获的TypeError:无法读取未定义的属性'setState'


constructor(props){
super(props);

this.state={
r:'',
message:''
};
this.setStateMessage = this.setStateMessage.bind(this);
}
setStateMessage (e){
e.preventDefault();
var test = this.state.message;

request
.post('http://127.0.0.1:5000/api/db')
.send({message: this.state.message})
.accept('application/json')
.withCredentials()
.end(function(err, res){
if(err)
throw err;
this.setState({ r: res.body.message });
});
}

render() {
return (
<div>
<div className='response'>
{this.state.r}
</div>
//form with input
</div>
)}

最佳答案

这是因为您是从函数中调用this.setState,所以this实际上是对您所在函数的引用。您需要存储对正确的this的引用,或者使用没有其箭头的箭头。自己的上下文,并从父上下文继承。所以:

setStateMessage (e){
e.preventDefault();
var test = this.state.message;
var self = this;

request
.post('http://127.0.0.1:5000/api/db')
.send({message: this.state.message})
.accept('application/json')
.withCredentials()
.end(function(err, res){
if(err) throw err;
self.setState({ r: res.body.message });
});
}


要么:

setStateMessage (e){
e.preventDefault();
var test = this.state.message;

request
.post('http://127.0.0.1:5000/api/db')
.send({message: this.state.message})
.accept('application/json')
.withCredentials()
.end((err, res) => {
if(err) throw err;
this.setState({ r: res.body.message });
});
}

关于reactjs - 使用superagent和React从API响应中获取setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37095252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com