У меня возникают трудности с получением данных из API в приложении React с помощью простого стандартного шаблона для получения данных API. Результатом, возвращаемым из журналов консоли, являются пустые массивы.
import React, {Component} from 'react';
import './App.css';
import Chart from './components/chart'
const API_URL = "http://ergast.com/api/f1/2016/1/results.json";
class App extends Component {
constructor(props) {
super(props)
this.state = {
results: [],
};
}
componentDidMount() {
fetch(API_URL)
.then(response => {
if (response.ok) {
return response.json()
}
else {
throw new Error ('something went wrong')
}
})
.then(response => this.setState({
results: response.MRData
})
)}
render() {
const {results} = this.state;
return (
<div className = "App">
<Chart data = {results}/>
</div>
);
}
}
export default App;
chart.js
import React from 'react';
import {XYPlot, XAxis, YAxis, VerticalGridLines, HorizontalGridLines, LineSeries} from 'react-vis';
const Chart = (props) => {
console.info(props.data);
const dataArr = props.data.map((d)=> {
return {x: d.RaceTable.Results.Driver.driverId, y: d.RaceTable.Results.position}
});
console.info(dataArr);
return (
<XYPlot
xType = "ordinal"
width = {1000}
height = {500}>
<VerticalGridLines />
<HorizontalGridLines />
<XAxis title = "Driver" />
<YAxis title = "Race Finish Position" />
<LineSeries
data = {dataArr}
style = {{stroke: 'violet', strokeWidth: 3}}/>
</XYPlot>
);
}
export default Chart;
На самом деле не могу понять, где я ошибся. Я правильно установил состояние с results: response.MRData, не так ли? (MRData - это ключ JSON.) Это структура json. Ссылка API: http://ergast.com/api/f1/2016/1/results.json
Пример ответа JSON
{
"MRData": {
"xmlns": "http://ergast.com/mrd/1.0",
"RaceTable": {
"Races": [
{
"season": "2008",
"round": "1",
}
},
"Results": [
{
"position": "1",
"Driver": {
"driverId": "hamilton",
"permanentNumber": "44",
"code": "HAM",
"url": "http://en.wikipedia.org/wiki/Lewis_Hamilton",
"givenName": "Lewis",
"familyName": "Hamilton",
"dateOfBirth": "1985-01-07",
"nationality": "British"
},
}
},
.
.
.
]
}
]
}
}
}
@ Jayce444 да.





Итак, вы регистрируетесь в верхней части вашего
chart.js, если вы регистрируете ответ в.then()выборки, он там пуст?