如何使用unirest在反应中设置状态

how to setState in react using unirest

我正在尝试使用 React 和 Unirest 从服务器发出获取请求,并将返回的信息存储在 setState 的变量中,但我总是遇到同样的错误。

TypeError: Cannot read property 'getData' of undefined.

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,而不是指向 class 实例, 使用这样的箭头函数

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

此外,您应该更改 getData -> setData

setData = data => {
  this.setState({ data})
}

或者只删除 setData 然后在回调中使用 setState

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