饼图未使用 Chart 在 React 中渲染

问题描述 投票:0回答:1

我在使用react-chartjs-2库和Chart.js在React组件中渲染饼图时遇到问题。图表的数据是从 API 获取的,一旦数据可用,图表就会呈现。然而,尽管数据已成功获取,但饼图并未在屏幕上呈现。

// Dashboard.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useUser } from '../UserContext';
import { AppBar, Toolbar, Typography, Container, Box } from '@mui/material';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Pie } from 'react-chartjs-2';
ChartJS.register(ArcElement, Tooltip, Legend);
const Dashboard = () => {
  const { userData } = useUser();
  const [genderCount, setGenderCount] = useState([]);
  const [loading, setLoading] = useState(true);
  let maleCount = 0;
  let femaleCount = 0;

  useEffect(() => {
    axios
      .get('https://randomuser.me/api/?results=10')
      .then(response => {
        const users = response.data.results;
        console.log(users)
        // Iterate over the users to count genders
        users.forEach(user => {
          if (user.gender === 'male') {
            maleCount++;
          } else if (user.gender === 'female') {
            femaleCount++;
          }
        });

        // Update the state with gender count
        // setGenderCount([
        //   { gender: 'male', count: maleCount },
        //   { gender: 'female', count: femaleCount }
        // ]);
        setLoading(false);
        console.log('male',maleCount)
        console.log('female',femaleCount)

      })
      .catch(error => {
        console.error('Error fetching data:', error);
        setLoading(false);
      });
  }, []);

  // Extract data for the pie chart
 const data = {
    labels: ['Male', 'Female'],
    datasets: [
      {
        label: '# of Votes',
        data: [maleCount,femaleCount],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',

        ],
        borderWidth: 1,
      },
    ],
  };

  return (
    <Container>
      <AppBar position="fixed">
        <Toolbar>
          <Box sx={{ flexGrow: 1 }}>
            <Typography variant="h6" component="div">
              Your Logo
            </Typography>
          </Box>
          <Typography variant="h6" component="div">
            {userData && `Welcome, ${userData.username}!`}
          </Typography>
        </Toolbar>
      </AppBar>

      <Box sx={{ marginTop: '4rem', width: '80%', margin: 'auto' }}>
        <h2>Dashboard</h2>
        {  (
          <div>
            {/* Display other user information */}
            
            {/* Conditionally render pie chart when data is available */}
            {loading ? (
              <p>Loading...</p>
            ) : (
              <div>
                <h3>Gender Counts</h3>
                <Pie data={data}/>
              </div>
            )}
          </div>
        )}
      </Box>
    </Container>
  );
};

export default Dashboard;
问题详情:

验证数据是否正确获取。 当数据可用时,加载状态设置为 false。 使用react-chartjs-2库中的Pie组件。 设置图表的宽度和高度。

问题详情: 即使确保已获取数据并将加载状态设置为 false,饼图也不会出现在屏幕上。我也尝试过调整图表的宽度和高度,但似乎并不能解决问题。

问题: 对于饼图为何未按预期呈现的任何见解或建议,我将不胜感激。我的代码是否存在我可能忽略的潜在问题?

谢谢您的帮助!

javascript reactjs chart.js
1个回答
0
投票

除了一个小问题之外,您的代码几乎是正确的。在第 51 行中,您传递了

maleCount
femaleCount
。但是这些值在这里不存在,这就是导致问题的原因。

相反,您需要使用

maleCount
状态传递
femaleCount
genderCount
的值。你应该像这样传递它:

data: [genderCount[0]?.count, genderCount[1]?.count]

这是更正后的代码:

// Dashboard.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { AppBar, Toolbar, Typography, Container, Box } from '@mui/material';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import { Pie } from 'react-chartjs-2';
ChartJS.register(ArcElement, Tooltip, Legend);
const Dashboard = () => {
  // const { userData } = useUser();
  const [genderCount, setGenderCount] = useState([]);
  const [loading, setLoading] = useState(true);
  let maleCount = 0;
  let femaleCount = 0;

  useEffect(() => {
    axios
      .get('https://randomuser.me/api/?results=10')
      .then((response) => {
        const users = response.data.results;
        console.log(users);
        // Iterate over the users to count genders
        users.forEach((user) => {
          if (user.gender === 'male') {
            maleCount++;
          } else if (user.gender === 'female') {
            femaleCount++;
          }
        });

        // Update the state with gender count
        setGenderCount([
          { gender: 'male', count: maleCount },
          { gender: 'female', count: femaleCount },
        ]);
        setLoading(false);
        console.log('male', maleCount);
        console.log('female', femaleCount);
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
        setLoading(false);
      });
  }, []);

  // Extract data for the pie chart
  const data = {
    labels: ['Male', 'Female'],
    datasets: [
      {
        label: '# of Votes',
        data: [genderCount[0]?.count, genderCount[1]?.count], // ✅ Made changes here
        backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)'],
        borderColor: ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)'],
        borderWidth: 1,
      },
    ],
  };

  return (
    <Container>
      <AppBar position='fixed'>
        <Toolbar>
          <Box sx={{ flexGrow: 1 }}>
            <Typography variant='h6' component='div'>
              Your Logo
            </Typography>
          </Box>
          {/* <Typography variant='h6' component='div'>
            {userData && `Welcome, ${userData.username}!`}
          </Typography> */}
        </Toolbar>
      </AppBar>

      <Box sx={{ marginTop: '4rem', width: '80%', margin: 'auto' }}>
        <h2>Dashboard</h2>
        {
          <div>
            {/* Display other user information */}

            {/* Conditionally render pie chart when data is available */}
            {loading ? (
              <p>Loading...</p>
            ) : (
              <div>
                <h3>Gender Counts</h3>
                <Pie data={data} />
              </div>
            )}
          </div>
        }
      </Box>
    </Container>
  );
};

export default Dashboard;

© www.soinside.com 2019 - 2024. All rights reserved.