typescript - 在chartJS中获取数据
问题描述
我基本上是在尝试通过后端服务器(python)获取数据并且我已经创建了我的图表前端,基本上我使用 useState 挂钩来存储我得到的数据,所以当我收到更新的数据时图表更新。可悲的是,我长期以来一直试图这样做,但没有成功。useState 中的“data”变量始终在控制台日志中返回 null 或 undefined,在图表中使用它会导致 [object object]
这是我的主页代码(在 react-typescript 中)我使用 useEffect 来呈现我的图表
function Home() {
const [data, setData] = React.useState([]);
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response =>{
console.log(response);
return response.json();
})
.then (response =>{
console.log(response);
setData(response)
// console.log(setData(response))
})
useEffect(() => {
const ctx = document.getElementById('myChart') as HTMLCanvasElement;
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [ {data}, {data}, 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
maintainAspectRatio: false,
responsive: true,
layout:{
padding:{
left:800,
top:0
}
},
scales: {
y: {
beginAtZero: true
}
}
}
});
return () => {myChart.destroy()}}, []);
return(
HTML Page)
解决方案
推荐阅读
- laravel - 如何缩短 eloquent 查询
- sql - SQL 语法查询 order by
- nginx - Cpanel Nginx 仍在监听 80 端口
- c# - 将 SQl 转换为 LINQ(使用 case 语句方法)
- javascript - Jquery,如何使用 jquery 添加隐藏元素
- javascript - 翻转卡片 HTML:单击时不会翻转或保持翻转
- java-8 - 使用项目反应器处理多个外部服务
- r - 在 R 中使用 For 循环生成向量
- reactjs - react-three-fiber 3D 对象(.obj)模型不投射任何阴影
- python - 明智地在列表组件列表中添加或减去元素