javascript - 无法显示来自 API 的数据
问题描述
我有一些图表(用 Graph js 制作),我想在其中显示数据。
似乎我可以获取它们并且数据显示在制作中,但我无法在实际图表中显示它们。我尝试了不同的方法,甚至直接在返回字段中映射它,但它仍然没有工作并且显示它是未定义的。
const API = 'http://127.0.0.1:5000/models/';
const DEFAULT_QUERY = 'Vno';
class App extends Component {
constructor(props) {
super(props);
this.state = {
chartData: {},
hits: [],
isLoading: false,
error: null
};
}
getChartData() {
const hits = this.state;
const nextMonths = ['February', 'March', 'April', 'June', 'July', 'August', 'September', 'October'];
this.setState({
chartData: {
labels: hits.pha,
datasets: [
{
label: 'Dataset',
fill: false,
lineTension: 0.1,
backgroundColor: ['rgba(243, 129, 129, 0.4)', 'rgba(75,192,192,0.4)',
'rgba(249, 237, 105, 0.4)',
'rgba(184, 59, 94, 0.4)',
'rgba(106, 44, 112, 0.4)',
'rgba(0, 184, 169, 0.4)',
'rgba(135, 133, 162, 0.4)'],
borderColor: '#fae3d9',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: '#212121)',
pointBackgroundColor: '#252a34',
pointBorderWidth: 3,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 5,
pointHitRadius: 10,
data: [50, 30, 40, 60]
}
],
}
})
}
componentDidMount() {
this.setState({ isLoading: true });
fetch(API + DEFAULT_QUERY)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Something went wrong ...');
}
})
.then(data => this.setState({ hits: data.hits, isLoading: false }))
.catch(error => this.setState({ error, isLoading: false }));
}
componentWillMount() {
this.getChartData();
}
render() {
const { hits, isLoading, error } = this.state;
if (error) {
return <p>{error.message}</p>;
}
if (isLoading) {
return <div className="react-spinner">
<MDSpinner size={100} />
</div>
}
return (
<div className="App">
<Navbar bg="light" variant="light">
<Navbar.Brand href="#">Aeroconseil</Navbar.Brand>
<Nav className="mr-auto">
</Nav>
</Navbar>
<hr className="hr-line"></hr>
<div className="container">
<Chart chartData={this.state.chartData} />
<LineGraph chartData={this.state.chartData} />
<ul>
{hits.map(hit =>
<li key={hit.name}>
<a>{hit.pha}</a>
</li>
)}
</ul>
</div>
</div>
);
}
}
export default App;
我希望显示来自 API 的数据,但它显示未定义。
解决方案
推荐阅读
- authorization - Postman 上的授权类型 Bearer Token
- parse-platform - 有没有办法限制查询中对象返回的键?
- javascript - 查找隐藏的父元素jQuery
- java - Java 正则表达式匹配范围内的数字
- c# - 使用 Prism 时如何允许 WPF 为 Window 控件解析 ContentTemplate?
- javascript - 如何使用角度动画始终将其向一个方向移动?
- visual-studio - 从 Visual Studio 发布到 Azure 时,“项目中不存在目标‘AddScheduledJob’”
- windows - Windows 10 主页上的 Docker
- apache-camel - features:uninstall -v 或 features:uninstall --verbose 未显示 Karaf 2.4.0.redhat-630310 中正在执行的操作
- javascript - 带有 DataTables 的 Javascript JSON 数据