[英]how to setState in react using unirest
I'm trying to make a get request from the server using React and Unirest and store the information that comes back inside a variable with setState
, but I always get the same error.我正在尝试使用 React 和 Unirest 从服务器发出 get 请求,并将返回的信息存储在带有setState
的变量中,但我总是遇到相同的错误。
TypeError: Cannot read property 'getData' of undefined.类型错误:无法读取未定义的属性“getData”。
export default class ApartmentsRow extends React.Component {
constructor(props) {
super(props);
this.state = {
data:[]
};
}
componentDidMount(){
var req = unirest("GET", "https://realtor.p.rapidapi.com/properties/detail");
req.query({
"listing_id": "608763437",
"prop_status": "for_sale",
"property_id": "4599450556"
});
req.headers({
"x-rapidapi-host": "realtor.p.rapidapi.com",
"x-rapidapi-key": "34b0f19259mshde1372a9f2958e5p13e3cdjsnf2452cd81a81"
});
req.end(function (res) {
if (res.error) throw new Error(res.error);
console.log(res.body);
this.getData(res.body.listing)
});
}
getData = (allData) =>{
this.setState({
data:allData
})
}
because this
in your callback point to the callback
, not point to the class instance, use an arrow function like this因为this
在您的回调中指向the callback
,而不是指向类实例,请使用这样的箭头函数
req.end(res => {
if (res.error) throw new Error(res.error);
this.setData(res.body.listing)
});
also, you should change getData
-> setData
此外,您应该更改getData
-> setData
setData = data => {
this.setState({ data})
}
or just remove the setData
then use setState
inside the callback或者只是删除setData
然后在回调中使用setState
req.end(res => {
if (res.error) throw new Error(res.error);
this.setState({ data: res.body.listing });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.