反应问题:如何使useEffect中的变量在useEffect之外接收?

时间:2020-08-07 20:45:53

标签: javascript reactjs

我正在使用useEffect来接收一个全局变量chart1,在钩子中,我将这个变量定义为带有一些数据和属性的Chart对象。但是,当我像下面的代码在钩子之外执行chart1.destroy()时,看不到chart1的更改,但是当我在useEffect中执行相同的操作时,将看到chart1的更改。我想查看挂钩外部图表的变化,以便通过挂钩将图表呈现到画布。有什么办法吗?

import React, { useEffect } from 'react';
import Chart from 'chart.js';
import { Card } from 'components/Card';
import { localDateTime, dateFilter } from 'helpers';

const red = '#644DFF';
const purple = '#F73F64';

const DailyTrafficCard = (props) => {
  const { store, capacity, data, setVar} = props;

  const lastSevenDays = Array(7)
    .fill()
    .map((_, i) => {
      const localdate = localDateTime(store);
      return localdate()
        .subtract(i, 'day')
        .format('YYYY-MM-DD[T]07:00:00[Z]');
    });
  //console.log('lastSevenDays',lastSevenDays);
  let chart1;
  useEffect(() => {
    const ctx = document && document.querySelector('#daily-traffic-chart');
    if (!ctx) {
      return;
    }
    chart1 = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: [],
        datasets: [{
          data: data[0],
          barThickness: 13,
          backgroundColor: (ctx) => {
            const idx = ctx && ctx.dataIndex;
            const val = ctx && ctx.dataset && ctx.dataset.data && ctx.dataset.data[idx];
            return val < 40 ? purple : red;
          }
        }]
      },
      options: {
        //events:[],
        intersect: false,
        legend: {
          display: false,
        },
        scales: {
          xAxes: [{
            type: 'time',
            offset: true,
            time: {
              unit: 'hour',
              displayFormats: {
                hour: 'HH',
              },
            },
            ticks: {autoSkip: false,
            },
            gridLines: {
              display: false,
            },
          }],
          yAxes: [{
            gridLines: {
              display: true,
            },
            ticks: {
              beginAtZero: false,
              max: capacity,
              stepSize: 5
            },
          }],
        },
      }
    });
    if (chart1){
      chart1.destroy();
    }
  }, [data,capacity]);

  const handleOnChange = (event) => {
    setVar(event.target.value);
  }

  return (
    <Card
      classname="DailyTrafficCard"
      icon={<span><i className="icon-user"/></span>}
      title={<h3>Daily Traffic Analytics</h3>}>
      <div className="daily">
        <div className="daily-head p-4 text-center">
          <select className="py-2 px-3" onChange={handleOnChange}>
            {lastSevenDays.map(date => (
              <option key={date} value={date}>{dateFilter(date, 'dddd')}</option>
            ))}
          </select>
        </div>

        <div className="px-8">
          {data && data.length > 0 && (
            <canvas width="250" id="daily-traffic-chart"></canvas>
          )}
        </div>
      </div>
    </Card>
  )
}

1 个答案:

答案 0 :(得分:0)

如果您想让变量影响您的视图,则它需要一个属性或一个状态。我不了解Chart,但我想您可以将聊天存储在一种状态下:

const [myChart, setMyChart] = useState();

然后在您的useEffect中将其与图表一起设置,销毁它时,只需将其设置为所需的值即可,destroy()会返回,如果确实返回了某些内容(我不会知道),或者根据需要设置为null,undefined等。