簡體   English   中英

無法讀取屬性“未定義的統計信息”

[英]cannot read property “statistics of undefined”

在此處輸入圖片說明 我試圖用axios + node.js進行api調用,我在控制台中獲取數據,但是當我嘗試檢索嵌套值時,我得到錯誤無法讀取未定義的屬性'statistics'。 在控制台中,當我將鼠標懸停在它上面時,我得到data.data。[0] .statistics.population_density.value但在我的代碼中它不起作用。 有人可以解釋imi做錯了什么嗎? 謝謝

 [
   data:
      {
        data: Array(1) {

          0: {

  {
    "statistics": {
      "population_density": {
        "source_name": "NASA Socioeconomic Data and Applications Center (SEDAC) – Hosted by CIESIN at Columbia University",
        "value": 13543,
        "description": "The number of inhabitants per square kilometer around this point."
      }
    },
    "location": {
      "latitude": 37.769456,
      "longitude": -122.429128
    }
  }
]


handleSelect = address => {
    this.setState({
        address,
    });

    console.log(this.state.address);

    geocodeByAddress(address)
        .then(res => getLatLng(res[0]))
        .then(({
            lat,
            lng
        }) => {
            this.setState({
                latitude: lat,
                longitude: lng,
                isGeocoding: false,
            });

            this.setState({
                isLoaded: true
            });
        })
        .catch(error => {
            this.setState({
                isGeocoding: false
            });
            console.log('error', error); // eslint-disable-line no-console
        });

    console.log(this.state.latitude);
    console.log(this.state.longitude);

    var param = {
        lat: this.state.latitude,
        long: this.state.longitude,
        temp: 1,
    };
    axios
        .post(`http://localhost:5000/search-data`, {
            param,
        })
        .then(data => {
            console.log(data);
            this.setState({
                value: data.data[0].statistics.population_density.value,
            });

        });

};

您需要data.data.data[0]

.then(data => {
        console.log(data);
        this.setState({
            value: data.data.data[0].statistics.population_density.value,
        });

    });

console.log(data)的輸出顯示,此對象(存儲在名為data的變量中)具有一個稱為data的屬性,而該屬性又又具有一個名為data的屬性。

我建議將data參數重命名為response因為那是axios實際為您提供的:

.then(response => {
    console.log(response);
    this.setState({
        value: response.data.data[0].statistics.population_density.value
    });
});

然后錯誤應該很明顯。 response不僅包含數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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