【问题标题】:Getting .map() not a function when trying to pass JSON to Vue尝试将 JSON 传递给 Vue 时获取 .map() 不是函数
【发布时间】:2021-05-27 07:22:18
【问题描述】:

我在后端创建了一个 api,并在 http://localhost:5000/result 上以 JSON 格式显示结果。我发现我需要一个 .js 文件来处理 api 并允许我在我的 Vue 组件中使用数据。这是我找到的解决方案:

import axios from 'axios';

const url = "http://localhost:5000/result";

class WeatherService {
    static getWeather() {
        return new Promise((resolve, reject) => {
            axios.get(url).then((res) => {
                try {
                    const data = res.data;
                    resolve(
                        data.map(weather => ({
                            ...weather
                        }))
                    );
                } catch (error) {
                    reject(error);
                }
            })
        })
    }
}

export default WeatherService;

我的 Vue 组件

<script>
import WeatherService from '../WeatherService';

export default {
  name: 'Result',
  data(){
    return {
      weather: [],
      error: ''
    }
  },
  async created() {
    try {
      this.weather = await WeatherService.getWeather();
    } catch (error) {
      this.error = error.message;
    }
  }
}
</script>

启动两者后,我得到data.map is not a function 并且无法使用任何数据。

编辑:我现在意识到 .map() 用于数组,我正在尝试将它用于 JSON 数据。什么是类似的解决方案?

编辑 2:Json 数据

{
  "coord": {
    "lon": -97.7431,
    "lat": 30.2672
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 82.15,
    "feels_like": 81.23,
    "temp_min": 80.01,
    "temp_max": 84.2,
    "pressure": 1015,
    "humidity": 37
  },
  "visibility": 10000,
  "wind": {
    "speed": 3.44,
    "deg": 0
  },
  "clouds": {
    "all": 1
  },
  "dt": 1614206313,
  "sys": {
    "type": 1,
    "id": 3344,
    "country": "US",
    "sunrise": 1614171738,
    "sunset": 1614212779
  },
  "timezone": -21600,
  "id": 4671654,
  "name": "Austin",
  "cod": 200
}

【问题讨论】:

    标签: json vue.js axios


    【解决方案1】:

    您需要的数据不需要任何映射,因此 Axios 回调应该按原样解析 API 响应:

    class WeatherService {
        static getWeather() {
            return new Promise((resolve, reject) => {
                axios.get(url).then((res) => {
                    resolve(res.data);
                })
            })
        }
    }
    

    请注意,axios.get() 已经返回了 Promise,因此您可以直接返回而不包装它:

    class WeatherService {
        static getWeather() {
            return axios.get(url).then(res => res.data)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-26
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多