为什么 useEffect 在启动时不渲染我的图表?

Why doesn't useEffect render my graph on startup?

我正在 React 中使用 ApexCharts 创建图表。我对两者都不熟悉,所以这可能很明显:当我第一次加载或重新加载网站时,我的图表没有呈现。但是,当我更改 UseEffect 内部的某些内容时,它确实会呈现。

编辑:认为这可能与 Async Axios 调用有关。组件在调用之前呈现。知道如何在不从 axios 中删除异步的情况下延迟它吗(这会破坏它)?

我的App.js:

import './App.css';
import React, { useEffect } from 'react';
import axios from 'axios'
import BarChart from './components/BarChart';
import GraphChart from './components/GraphChart';
import _, { orderBy } from 'lodash'



const config = {
'Content-Type': 'application/json',
"Accept": "application/json",
}

const arrayElements = [];

const App = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(async () => {
const { data } = await axios({ url: 'http://192.168.*/', method: 'GET', data: null, withCredentials: true, headers: config })

data.value.forEach(d => {

  const IdNumber= d._IdNumber
  const dateValue = d._dataValue
  arrayElements.push({ IdNumber, dateValue })
})

}, [])

return (
<div className="app">
<div className="example">
<div id="wrapper">`
<BarChart
arrElements={arrayElements}
/>
</div>
<div id="wrapper">
<GraphChart
arrElements={arrayElements}
/>
</div>
</div>
</div>
);
}

export default App;

我的图表:

import React, { useEffect, useState } from 'react' 
import Chart from 'react-apexcharts'
import _ from 'lodash'

const GraphChart = ({ arrElements}) => {
const [category, setCategory] = useState([])
const [data, setData] = useState([])

useEffect(() => {
    let series = [];
    let categories = [];
    let orderedArrElements= _.orderBy(arrElements, ['dateValue'], ['asc', 'desc'])
    for (let i = 0; i < orderedArrElements.length; i++) {
        series.push(
            orderedArrElements[i].IdNumber
        )
        categories = categories.concat(orderedArrElements[i].dateValue)
    }
    console.log(categories)

    setCategory(categories)
    setData(series)
    console.log("is called")
}, [arrElements])

return (
    <div>
        <Chart
            options={{
                chart: {
                    id: "basic-graph",
                },
                stroke: {
                    curve: 'smooth',
                    colors: ['#00BAEC']
                },
                grid: {
                    row: {
                        colors: ['#f3f3f3', 'transparent'],
                        opacity: 0
                    },
                },
                fill: {
                    gradient: {
                        enabled: true,
                        opacityFrom: 0.65,
                        opacityTo: 0
                    }
                },
                markers: {
                    size: 5,
                    colors: ["#000524"],
                    strokeColor: "#00BAEC",
                    strokeWidth: 3
                },
                dataLabels: {
                    enabled: false
                },
                xaxis: {
                    categories: category,
                    labels: {
                        style: {
                            colors: '#fff'
                        }
                    }
                },
                yaxis: {
                    labels: {
                        style: {
                            colors: '#fff'
                        }
                    }
                },
            }}
            series={[{
                name: "ID",
                data: data
            }
            ]}
            type="area"
            width={2000}
            height={1000} />
    </div>


   )
}

export default GraphChart

当所有代码都在 App.js 中时它确实呈现了。

您应该使用状态来跟踪 arrayElements

按照您现在的方式,图形组件是使用 arrayElements = [] 呈现的。在下一步中,数据将附加到 arrayElements,但 React 不会注意到这一点,因此不会重新渲染图表。

如果您将 arrayElements 初始化为 const [arrayElements, setArrayElements] = useState([]) 并按以下更新数据,那么 React 将注意到更改并在收到数据后立即重新渲染图形组件。

const newData = data.value.map(d => {

  const IdNumber= d._IdNumber
  const dateValue = d._dataValue
  return { IdNumber, dateValue }
})
setArrayElements(newData)