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

Recharts动态设置dataKey后折线图无折线显示问题求助

Recharts动态添加dataKey时折线不显示的解决方法

核心问题

你在productArray.map的回调里没有返回renderLineChart(key)生成的<Line>组件,导致React没有把这些折线元素渲染到图表中。

修复代码

把map的回调改成带返回值的形式:

{productArray.map((key) => {
  return renderLineChart(key);
})}

或者更简洁的箭头函数直接返回写法:

{productArray.map((key) => renderLineChart(key))}

额外优化:简化productArray的生成逻辑

你当前获取productArray的方式冗余,由于所有数据项结构一致,直接取第一个对象的keys并过滤掉name即可,无需遍历整个数据集:

const productArray = Object.keys(productDataset[0]).filter(item => item !== "name");

完整修复后的代码

const productDataset= [
  {
    name: "2023-02-18",
    flavor1: 14,
    flavor2: 10,
    flavor3: 9,
  },
  {
    name: "2023-02-19",
    flavor1: 7,
    flavor2: 9,
    flavor3: 2,
  },
  {
    name: "2023-02-20",
    flavor1: 18,
    flavor2: 21,
    flavor3: 15,
  },
];

const renderLineChart = (key) => (
  <Line type="monotone" dataKey={key} stroke="#8884d8" activeDot={{ r: 8 }} />
);

function renderChart() {
  const productArray = Object.keys(productDataset[0]).filter(item => item !== "name");
  
  return (
    <ResponsiveContainer width="100%" height={400}>
      <LineChart
        width={1200}
        height={500}
        data={productDataset}
        margin={{
          top: 5,
          right: 30,
          left: 20,
          bottom: 5,
        }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        {productArray.map((key) => renderLineChart(key))}
      </LineChart>
    </ResponsiveContainer>
  )
}

手动调用生效的原因

手动写<Line>时,你直接将组件作为子元素传递给了<LineChart>;而动态生成时因未返回组件,相当于没有传递任何折线子组件,所以看不到折线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:37:41