首页 > 解决方案 > 如何使用 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
    })
}

标签: javascriptreactjsrequestunirest

解决方案


因为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})
}

或者只是删除回调中的setDatathen 使用setState

req.end(res => {
  if (res.error) throw new Error(res.error);
  this.setState({ data: res.body.listing });
});

推荐阅读