簡體   English   中英

如何使用 unirest 在反應中設置狀態

[英]how to setState in react using unirest

我正在嘗試使用 React 和 Unirest 從服務器發出 get 請求,並將返回的信息存儲在帶有setState的變量中,但我總是遇到相同的錯誤。

類型錯誤:無法讀取未定義的屬性“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然后在回調中使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM