我正在尝试将json状态从组件api传递到组件图表。当我尝试使用日志控制台时,它会显示数据,但在构造函数中,如果我在控制台中尝试使用this.state.json而不是this.props.json,似乎没有这些数据。我正在尝试尝试从api组件获取this.state.json中的数据,并将其传递给图表组件(当我设置json:this.props.json时)。但是图表中的this.state.json是空的。
import React, { Component } from 'react';
import axios from 'axios';
import Hlavnicards from './Hlavnicards';
import Datatable from './Datatable';
import Chart from './Chart';
import Countrypicker from './Countrypicker';
class Api extends Component {
constructor(props) {
super(props);
this.state = {
countries: [],
global: [],
date: [],
chartdata: [],
json: []
};
}
componentDidMount() {
axios.get(`https://covid19.mathdro.id/api/daily`)
.then(response => response.data)
.then((data) => {
this.setState({ json: data })
})
axios.get(`api/corona2`)
.then(response => response.data)
.then((data) => {
this.setState({ countries: data.Countries })
this.setState({ global: data.Global })
this.setState({ date: data.Date })
})
}
render() {
return (
<div>
<div class= "p-col-12"><Hlavnicards currentDate = {this.state.date} summary = {this.state.global} /></div>
<div class= "p-col-12"><Countrypicker /></div>
<div class= "p-col-12"><Chart json = {this.state.json} /></div>
<div class= "p-col-12"><Datatable summaryCountries = {this.state.countries} /></div>
</div>
);
}
}
export default Api;
import React, { Component } from 'react';
import { Card } from 'primereact/card';
import C3Chart from 'react-c3js';
import 'c3/c3.css';
import axios from 'axios';
class Charts extends Component {
constructor(props) {
super(props);
this.state = {
json: this.props.json,
keys: {
x: 'reportDate',
value: ['totalConfirmed', 'deaths.total']
},
names: {
totalConfirmed: 'Infected',
'deaths.total': 'Deaths'
},
types: {
totalConfirmed: 'area-spline',
'deaths.total': 'area-spline'
// 'line', 'spline', 'step', 'area', 'area-step' are also available to stack
},
colors: {
totalConfirmed: 'red',
'deaths.total': 'black',
},
zoom: {
enabled: true
}
};
};
render() {
console.log(this.props.json);
return (
<div class="p-grid">
<div class="p-col-6" style={{ textAlign: 'center' }}>
<Card>
<C3Chart axis={{
x: {
type: 'timeseries',
label: {
text: 'Date',
position: 'outer-center'
}
},
y: {
label: {
text: 'Number of people',
position: 'outer-middle'
}
},
}} data={this.state} />
</Card>
</div>
</div>
);
}
}
export default Charts;
答案 0 :(得分:0)
如果您注意到班级名称是Charts,并且将其称为Chart
自从笔直开始,请按以下方式致电:
this.props.json
无需声明或其他任何内容
答案 1 :(得分:0)
我认为这样做更好
axios.get(`https://covid19.mathdro.id/api/daily`).then(response => {
this.setState({ json: response.data });
});
它对我有用,对于第二个API可以做到