在功能性 React 组件中使用 Chart.js,不允许我切换数据:"properties undefined"

Using Chart.js in functional React component, not allowing me to toggle data: "properties undefined"

我正在尝试在 Chart.js 图表中生成动态数据,但如何使图表常量可用于切换函数?

图表显示正常,但我根本无法更新它。我相信这是由于范围界定。我如何 return Chart.js 对象到主函数?

代码:

import React, { useContext, useEffect, useState } from "react";
import "./questions_trends.css";
import axios from 'axios';
import ReactTooltip from 'react-tooltip';

import { Chart } from "chart.js";

function Trends(){

    const user_context = useContext(UserContext)
    const [positiveChart, setPositiveChart] = React.useState(undefined);

    function makeChart(data){

        // Create the trends chart
        // positive_trend = 
        setPositiveChart = new Chart('positiveChart', {
            type: 'bar',
            data: { 
                labels: data.positive,
                datasets: [
                {
                    label: 'Team Positive',
                    data: data.team_positive,
                    backgroundColor: data.color
                },
                {
                    label: 'You Positive',
                    data: data.positive,
                    backgroundColor: data.color
                }]
            },
            options: {
            }
        }); 
    }

    function toggle(value) {
        if(positiveChart.isDatasetVisible(value)){
            positiveChart.hide(value)
        }

        if(!positiveChart.isDatasetVisible(value)){
            positiveChart.show(value)
        }
    }

    useEffect( async () => {
        let result = await axios.get("/api/monthly_tones")
            makeChart(result.data)
    }, []);


    useEffect( async () => {
        return positiveChart.destroy()
    }, []);

    //Render to Dom
    
    return (                    
        <div className="question_positivity_container">
            <canvas id="positiveChart" width="auto" height="70vh"></canvas>

            <button onClick={() => toggle(0)}>See All Cratic</button>
        </div>
    );
};

export default Trends;

toggle 和 useEffect 函数不起作用:TypeError: Cannot read properties of undefined (reading 'isDatasetVisible')

我认为这是因为 positiveChartengagedChart 不在他们的范围内。我该如何解决这个问题??

感谢任何帮助。

--- 更新

解决方案需要在 makeChart() 函数中使用 const chart = new Chart({}),然后将 chart 推入如下状态:setPositiveChart(chart).

这更新了函数状态并使变量随处可用。

我接受了下面的答案,因为这是正确的方法,并且让我得到了答案。感谢您的帮助!

你的问题是 positiveChart 不在你的其他函数的范围内,因为你在 makeChart 中声明了它。为了解决这个问题,您必须像这样在 react useState 中使用它:

const [positiveChart, setPositiveChart] = React.useState(undefined);

然后在 makeChart 中,您可以使用 setPositiveChart 来创建它。之后您将能够在 useEffect 函数中正确访问它。

您可以在 React docs 关于状态挂钩中阅读更多相关信息。