javascript - 如何使用 unirest setState 做出反应
问题描述
我正在尝试使用 React 和 Unirest 从服务器发出获取请求,并将返回的信息存储在带有 的变量中setState
,但我总是遇到同样的错误。
TypeError:无法读取未定义的属性“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
})
}
解决方案
因为this
在你的回调指向the callback
,而不是指向类实例,使用这样的箭头函数
req.end(res => {
if (res.error) throw new Error(res.error);
this.setData(res.body.listing)
});
另外,你应该改变getData
->setData
setData = data => {
this.setState({ data})
}
或者只是删除回调中的setData
then 使用setState
req.end(res => {
if (res.error) throw new Error(res.error);
this.setState({ data: res.body.listing });
});
推荐阅读
- android - 使用expo在android设备中打开反应本机应用程序时出错
- python - 根据给定条件将新列添加到现有数据框列
- django - django设置默认时区
- reactjs - 已解决:我试图在反应中将更新数据从父级传递给子级,但它没有在子组件的功能中更新
- database - Mongoose:TypeError:模式路径`guildId.type`的值无效,得到值“未定义”
- javascript - 仅用于数据结构和数据库的前端(React)解决方案
- python - 如何转换宽数据框以绘制特定数据
- regex - 正则表达式在文本文件中突出显示高于 85% 红色的百分位数
- flyway - 如何创建脚本或 Flyway 可以配置为每次使用 SQL 回调调用它?
- spartacus-storefront - 斯巴达克斯 2.1.9 在 2.0.0 之后的购物车效果问题