首页 > 解决方案 > 在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)

标签: typescriptreact-hooks

解决方案


推荐阅读