javascript - React ChartJS Scatter Plot - 无法绘制数据
问题描述
我正在尝试使用 chartJS 生成散点图。情节不会图表。当我通过声明数据手动输入数据时,它工作正常,
var scatter = [
{ x: 65, y: 75 },
{ x: 59, y: 49 },
{ x: 80, y: 90 },
{ x: 81, y: 29 },
{ x: 56, y: 36 },
{ x: 55, y: 25 },
{ x: 40, y: 18 },
]
但是当我通过 API 调用获取数据并将数据推送到数组时,它就不起作用了。有什么建议么?我怀疑它与如何将数据推送到阵列上有关,但不确定出了什么问题。
谢谢
下面的最小解决方案
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [scatterData, setScatterData] = useState({});
const chart = () => {
var scatter = [];
axios.get('http://dummy.restapiexample.com/api/v1/employees')
.then(res => {
let temp = res.data.data
temp.forEach( i=> {
let age = parseInt(i.employee_age)
let salary = parseInt(i.employee_salary)
scatter.push({"x": age,
"y": salary})
})
}).catch(err => {
console.log(err)
})
console.log(scatter)
setScatterData({
datasets: [
{
label: 'test',
fill: true,
backgroundColor: 'rgba(75,192,192,0.4)',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 10,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 3,
pointHitRadius: 10,
data: scatter,
backgroundColor: [
'rgba(75,192,192,0.6)'
],
borderWidth: 4
}
]
});
}
useEffect(() ={
chart()
},[])
return (
<div className ="container-fluid">
<div class="row">
<div className ="col-md-12">
<Scatter data={scatterData}/>
</div>
</div>
</div>
)
};
解决方案
将所有数据从 api 推送到散点数组后,尝试在图表对象/实例上调用更新方法
推荐阅读
- html - ReactJS - How To Setup 3 Divs One On-Top Of The Other?
- javascript - node.js 中的 setInterval 是否在计算机入睡时开始运行?
- python - python中最大的日期时间是多少?
- python - 使用上下文管理器选择数据库或文件处理程序
- java - 连续打开 2 个甜蜜警报对话框时应用程序冻结
- html - 取消隐藏存档网页上的列
- java - 异常:从线程“main”中的 UncaughtExceptionHandler 抛出 java.awt.HeadlessException
- reactjs - 在 React 中,是否有一种优雅的方式可以在 RESTful 编辑 url 中使用 id 并将相应的对象加载到我的组件的初始状态中?
- macos - 在 macOS 上的 Catalyst 中聚焦集合视图中的初始项目
- python - 从字典中的数据框中获取平均值