You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ApexCharts时间戳与对应Sender/Receiver数据映射问题求助

解决ApexCharts交易数据时间戳映射异常问题

你的核心问题是把Sender和Receiver的数据拆分成两个独立数组,同时重复添加时间戳到timeData,导致X轴分类与系列数据的长度、时间对应关系完全混乱。ApexCharts处理多系列带独立时间戳的数据时,不能用共享的categories,正确的做法是让每个系列的每个数据点都携带自身的时间戳。

修复步骤:

  • 废弃全局的receiverData、senderData、timeData,改用组件内状态存储处理好的系列数据
  • 处理接口数据时,为每个交易记录生成[时间戳, 代币数量]格式的数组元素,分别归类到Sender/Receiver系列
  • 移除xaxis的categories配置,ApexCharts会自动从数据点的时间戳生成X轴刻度

修改后的完整代码:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import ReactApexChart from 'react-apexcharts';
import { Card, CardContent, Stack, Typography } from '@mui/material';
import SsidChartOutlinedIcon from '@mui/icons-material/SsidChartOutlined';

export default function GraphCard() {
  const [seriesData, setSeriesData] = useState([
    { color: '#000073', name: 'Received', data: [] },
    { color: '#CA9026', name: 'Sent', data: [] }
  ]);

  const showData = () => {
    axios.get('http://localhost:8006/api/v2/user/transactions').then(function (res) {
      const result = res.data.data;
      if (result?.data) {
        const received = [];
        const sent = [];
        
        result.data.forEach(obj => {
          // 确保时间戳是毫秒级数值,若后端返回ISO字符串则转换
          const timestamp = new Date(obj.date).getTime();
          if (obj.role === 'Sender') {
            sent.push([timestamp, obj.tokens]);
          } else if (obj.role === 'Receiver') {
            received.push([timestamp, obj.tokens]);
          }
        });

        setSeriesData([
          { ...seriesData[0], data: received },
          { ...seriesData[1], data: sent }
        ]);
      } else {
        console.log('无有效数据');
      }
    }).catch(err => {
      console.error('接口请求失败:', err);
    });
  };

  const chartOptions = {
    chart: {
      height: 280,
      type: 'area'
    },
    dataLabels: {
      enabled: false
    },
    stroke: {
      curve: 'smooth'
    },
    xaxis: {
      type: 'datetime',
      // 移除categories,由数据点的时间戳自动生成
    },
    yaxis: {
      title: {
        text: '代币数量' // 补充Y轴标题,提升可读性
      }
    },
    tooltip: {
      x: {
        format: 'dd/MM/yy HH:mm'
      },
    },
  };

  useEffect(() => {
    showData();
  }, []);

  return (
    <Card>
      <CardContent display='flex' sx={{ flexDirection: 'column' }}>
        <Stack flexDirection='row' alignItems="center" gap={1}>
          <SsidChartOutlinedIcon sx={{ color: "text.secondary" }} />
          <Typography sx={{ fontSize: 15, fontWeight: 'bold' }} color="text.secondary" gutterBottom>
            Recent Transactions
          </Typography>
        </Stack>
        <div id="chart">
          <ReactApexChart options={chartOptions} series={seriesData} type="area" height={280} />
        </div>
      </CardContent>
    </Card>
  );
}

关键改动说明:

  1. 数据格式调整:每个系列的数据改成[timestamp, value]的二维数组,让每个数据点自带时间戳,彻底解决时间与数值的关联问题
  2. 状态管理优化:用组件内状态seriesData存储系列数据,避免全局变量导致的渲染异常
  3. 时间戳处理:将后端返回的日期字符串转换为毫秒级时间戳,确保ApexCharts能正确解析
  4. 移除冗余配置:删除xaxis的categories,让图表自动根据数据点生成X轴刻度

内容的提问来源于stack exchange,提问作者badcoder01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 00:25:18