Почему я потерял свой график. js, когда я делаю новый рендер - PullRequest
0 голосов
/ 31 марта 2020

Привет, у меня есть проблема в моем коде, позвольте мне преодолеть то, что я получил ...

import React, { memo, useEffect } from 'react';
import Chart from "chart.js";
/* redux-hook */
import { useSelector } from 'react-redux'

const lineChart = memo(({ data, labels, NewValue }) => {
    /* ----------------------------------VARIABLES REDUX------------------- */
    const { clase } = useSelector(state => state)
    /* ----------------------------------VARIABLES REDUX -------------------*/
    const chartRef = React.createRef();

    let myAreaChart, backColor, color, gradientFill, myChartRef;
    useEffect(() => {
      const  myChartRef = chartRef.current.getContext("2d")
        console.log("otra vez?",data, labels, NewValue)
        if (clase === 'content-layout active') {
            backColor = 'white'
            color = 'white'
        } else {
            gradientFill = myChartRef.createLinearGradient(500, 0, 100, 0);
            gradientFill.addColorStop(1, "#cb2d3e");
            gradientFill.addColorStop(0, "#ef483a");
            backColor = gradientFill
            color = '#C4C4C4'
        }
         myAreaChart = new Chart(myChartRef, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    data: data,
                    fill: true,
                    backgroundColor: backColor,
                    borderWidth: 'none',
                    color: 'white'
                }]
            },
            /* OPTIONS */
            options: {
                maintainAspectRatio: false,
                legend: {
                    display: false,
                },
                scales: {
                    yAxes: [{
                        gridLines: {
                            drawBorder: false,
                            display: false,
                        },
                        ticks: {
                            display: false,
                            beginAtZero: true
                        }
                    }],
                    xAxes: [{
                        gridLines: {
                            drawBorder: false,
                            display: false,
                        },
                        ticks: {
                            fontColor: color,
                            fontSize: 14,
                            stepSize: 1,
                            beginAtZero: true
                        }
                    }],
                }
            }
            /* OPTIONS */
        });
    }, []);

    useEffect(() => {
        if (NewValue !== 0) {
            myAreaChart.data.labels.shift()
            myAreaChart.data.datasets[0].data.shift()
            myAreaChart.data.labels[data.length] = "";
            myAreaChart.data.datasets[0].data[data.length] = NewValue;
            myAreaChart.update();
        }
    }, [NewValue]); 


    return (
        <div style={{ height: '350px', width: "350px" }}>
            <canvas ref={chartRef} id="myChart" ></canvas>
        </div>
    );
});

export default lineChart;

Проблема возникает, когда я пытаюсь сделать функцию обновления на графике, только функцию обновления прислушивается к изменению указанного значения c, которое передается свойствами, бывает, что когда это значение действительно изменяется, я теряю весь свой график, код выдает мне эту ошибку.

> lineChart.js:75 Uncaught TypeError: Cannot read property 'data' of undefined
    at lineChart.js:75
    at commitHookEffectListMount (react-dom.development.js:19764)
    at commitPassiveHookEffects (react-dom.development.js:19802)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at flushPassiveEffectsImpl (react-dom.development.js:22884)
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11061)
    at flushPassiveEffects (react-dom.development.js:22851)
    at react-dom.development.js:22730
    at workLoop (scheduler.development.js:597)
    at flushWork (scheduler.development.js:552)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:164)

an if i try to check whats happend with my graph... i got this 

> Chart {id: 0, ctx: CanvasRenderingContext2D, canvas: canvas#myChart.chartjs-render-monitor, config: {…}, width: 350, …} lineChart.js:74 (the first time it renders)
----------
> undefined lineChart.js:74 (the second time it renders)
----------

1 Ответ

0 голосов
/ 31 марта 2020

я решаю свою проблему, просто делая theupdate внутри функции запроса

  useEffect(() => {
        let interval,aux=[],count=0;
        if(clase==='content-layout active'){
             interval = setInterval(() => {
                axios
                .get( `/custom/balance`)
                .then(response => {
                        if(response.data!==undefined && response.data.length>0 ){
                            aux=response.data.slice(response.data.length-15)
                            setBalance(response.data.slice(response.data.length-15)) 
                            setnewValue(aux[aux.length-1].balance)
                            if(count%3==0){
                                myAreaChart.data.labels.shift()
                                myAreaChart.data.datasets[0].data.shift() 
                            }
                            myAreaChart.data.labels.push("");
                            myAreaChart.data.datasets[0].data.push(aux[aux.length-1].balance);
                            count+=1
                            myAreaChart.update();
                        }
                    }
                ).catch(error=>{
                    console.log(error)
                })
              }, 2000);
        }
    return()=>{
        clearInterval(interval); 
    } 
    // eslint-disable-next-line
    }, [clase]);
...