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

Recharts Tooltip显示异常求助:如何实现目标展示效果?

问题分析与解决方案

你的Tooltip显示异常的核心原因是传入LineChart的data格式不符合Recharts要求:

当前你生成的data是一个仅包含单个对象的数组,该对象的tanggal和hit都是数组类型,这会导致Recharts无法正确解析每个数据点的对应关系,最终Tooltip拿到的payload[0].value是整个hit数组,而非单个数据点的数值。

修正步骤

1. 调整数据格式

Recharts的LineChart要求data是对象数组,每个对象对应一个X轴数据点,包含该点的横轴值和纵轴值。

把原代码中的:

const data = [
  {
    tanggal: hasil.map((item) => item.timestamp),
    hit: hasil.map((item) => item.count),
  },
];

替换为:

const data = hasil.map(item => ({
  tanggal: item.timestamp,
  hit: item.count
}));

同时注意:原reduce的初始值用了[](数组),这是错误的,应该改为{}(对象),否则会导致acc类型错误,无法正确统计每日数据:

const hasil = Object.values(
  dataKey.reduce((acc, curr) => {
    if (acc[curr["@timestamp"].split("T")[0]] == null) {
      acc[curr["@timestamp"].split("T")[0]] = {
        message: curr.message,
        timestamp: curr["@timestamp"].split("T")[0],
        count: 0,
      };
    }
    acc[curr["@timestamp"].split("T")[0]].count++;
    return acc;
  }, {}) // 这里从[]改为{}
);

2. 优化CustomTooltip(按需调整)

如果需要和期望效果一致,显示单个数值或同时显示日期,可修改Tooltip组件:

const CustomTooltip = ({ active, payload }) => {
  if (active && payload && payload.length) {
    return (
      <div className="custom-tooltip w-fit h-fit p-2 m-0 bg-white drop-shadow-xl items-center rounded-xl">
        {/* 显示单个点击数 */}
        <p className="label p-0 m-0 text-sm font-bold">{payload[0].value}</p>
        {/* 若需显示日期,添加下面一行 */}
        {/* <p className="label p-0 m-0 text-sm text-gray-500">{payload[0].payload.tanggal}</p> */}
      </div>
    );
  }
  return null;
};

3. 验证XAxis配置

原XAxis的dataKey="tanggal"无需修改,现在每个数据对象都有tanggal字段,Recharts可以正确渲染横轴标签。

修正后效果

调整后,Tooltip的payload会对应单个数据点的信息,payload[0].value将显示该点的点击数,符合你期望的展示效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:13:54