如何更新饼图上的系列

How to update series on pie chart

在我的index.js中我定义了饼图:

import pieChart1 from './chart/pie-chart-1';

然后这里在render()函数下添加:

        <Col md={6}>
                <Card>
                    <Card.Header>
                        <Card.Title as="h5">BALANCE</Card.Title>
                    </Card.Header>
                    <Card.Body>
                        <Chart {...pieChart1} />
                    </Card.Body>
                </Card>
            </Col>

我在 ./chart/pie-chart-1.js 中定义了一个饼图:

export default {
    height: 320,
    type: 'pie',
    options: {
        labels: ['Call', 'Put'],
        colors: ['#4680ff', '#0e9e4a'],
        legend: {
            show: true,
            position: 'bottom',
        },
        dataLabels: {
            enabled: true,
            dropShadow: {
                enabled: false,
            }
        },
        responsive: [{
            breakpoint: 480,
            options: {
                chart: {
                    width: 200
                },
                legend: {
                    position: 'bottom'
                }
            }
        }]
    },
    series: [50, 50]

我有一个调用 API 的函数,执行一些数学运算并将值保存到 state。

  this.setState({CallPrem : callPrem, PutPrem : putPrem})

此时,我想用这些值更新饼图....我该怎么做?基本上想要 series[0] 有 callPrem 值和 series[1] 有 putPrem.

请原谅我的菜鸟式行话,这是我第一次使用 reactjs,我喜欢它,但我正在慢慢拼凑所有这些是如何工作的。谢谢

您有多个选项来更新图表。

第一个也是推荐的方法是更新传递给组件的道具

const newOptions = {
  ...pieOptions,
  options: {
    ...options,
    labels: [newLabels]
  },
  series: [newSeries]
}

更新道具会自动re-render图表。


另一种方法是使用核心 ApexCharts.exec() 功能。为此,您需要先在 pie-chart-1.js 文件中设置 chart-id。

export default {
    height: 320,
    type: 'pie',
    options: {
      chart: {
        id: "chart-id"
      }
    }
}

一旦你设置了图表id,你就可以调用下面的方法

ApexCharts.exec('chart-id', 'updateOptions', {
  series: newSeries,
  labels: newLabels
})