使用axios处理JSON数据时出现问题



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

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设置为响应您的请求而获得的整个数据对象。请改用数据对象的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 }));
}

最新更新