【问题标题】:Having issues using axios to handle my JSON data使用 axios 处理我的 JSON 数据时遇到问题
【发布时间】:2019-04-01 04:51:30
【问题描述】:

我正在尝试从这些数据中设置状态,

var axios = require('axios');
import Trails from './trails';
import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
        trails: []
    } 
} 
componentWillMount() {
      axios
      .get('https://www.mtbproject.com/data/get-trails-by-id?ids=2081068,830442%208013961&key=(API-KEY)')
      .then(response => response.data)
      .then(trails => this.setState({trails}));
    }

看起来像这样:

{
    "trails": [
        {
            "id": 2081068,
            "name": "San Dieguito River Park - Bernardo Bay\/ Piedras Pintadas Trail",
            "type": "Featured Ride",
            "summary": "Sweet little loop of singletrack trails.",
            "difficulty": "blue",
            "stars": 3.6,
            "starVotes": 24,
            "location": "Escondido, California",
            "url": "https:\/\/www.mtbproject.com\/trail\/2081068\/san-dieguito-river-park-bernardo-bay-piedras-pintadas-trail",
            "imgSqSmall": "https:\/\/cdn-files.apstatic.com\/mtb\/2148715_sqsmall_1372258680.jpg",
            "imgSmall": "https:\/\/cdn-files.apstatic.com\/mtb\/2148715_small_1372258680.jpg",
            "imgSmallMed": "https:\/\/cdn-files.apstatic.com\/mtb\/2148715_smallMed_1372258680.jpg",
            "imgMedium": "https:\/\/cdn-files.apstatic.com\/mtb\/2148715_medium_1372258680.jpg",
            "length": 8.2,
            "ascent": 570,
            "descent": -567,
            "high": 488,
            "low": 317,
            "longitude": -117.0766,
            "latitude": 33.0512,
            "conditionStatus": "All Clear",
            "conditionDetails": "Dry",
            "conditionDate": "2018-09-11 09:12:17"
        }
    ],
    "success": 1
}

然后我尝试像这样映射它:

 render() {
    return (
  <div className='App'>
  <div className="container">
  <div className="jumbotron">
      <h4>Mtb</h4>
      <p>Trails:</p>
    </div>
    {this.state.trails.map(trail => (
        <Trails key={trail.id} 
        conditions={trail.conditionDetails}
        />
    ))
    }
  </div>
  </div>
    );
  }
}

然后我收到一条错误消息,指出我的 map 方法不是函数。有人可以指出我做错了什么吗?

当我 console.log 我的状态时,它似乎没有被设置,这可能是问题所在并解释了它为什么不起作用?

【问题讨论】:

  • 您没有访问响应数据中的 trails 属性,只是命名无用的参数。

标签: node.js json reactjs axios


【解决方案1】:

您将trails 设置为响应您的请求而获得的整个数据对象。请改用数据对象的trails 属性。

componentWillMount() {
  axios
    .get('https://www.mtbproject.com/data/get-trails-by-id?ids=2081068,830442%208013961&key=(API-KEY)')
    .then(response => this.setState({ trails: response.data.trails }));
}

【讨论】:

  • 谢谢你,Tholle!
猜你喜欢
  • 1970-01-01
  • 2014-01-07
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-17
相关资源
最近更新 更多