简体   繁体   English

Recharts tickFormatter 不格式化日期

[英]Recharts tickFormatter not formatting date

I have a date structure like this我有这样的日期结构

在此处输入图像描述

a tick formatter like this像这样的刻度格式化程序

  const formatXAxis = tickFormat => {
    return moment(tickFormat).format('DD/MM/YY');

} }

and my chart looks like this我的图表看起来像这样

          <LineChart
        width={600}
        height={300}
        data={data.list}
        margin={{ top: 5, right: 20, bottom: 5, left: 0 }}
      >
        <Line 
          type="monotone" 
          dataKey="components.co" 
          stroke="#8884d8" />
        <XAxis
          dataKey="dt"
          tickFormatter={formatXAxis}
          domain={['dataMin', 'dataMax']}
          type="number"
        />
        <YAxis />
        <Tooltip />
      </LineChart>

But when the chart is rendered it reads in the dt as the timestamp, but the converter isn't converting the timestamp, it is just setting the epoch start date in each case但是当图表被渲染时,它在 dt 中读取为时间戳,但转换器没有转换时间戳,它只是在每种情况下设置纪元开始日期

在此处输入图像描述

I've looked at other examples of people doing the same thing but I can't see where I'm going wrong here.我看过其他人做同样事情的例子,但我看不出我在哪里出错了。 Any help is appreciated.任何帮助表示赞赏。 Let me know if I've missed any info that might be relevent.如果我错过了任何可能相关的信息,请告诉我。 Thanks!谢谢!

You have a couple of problems with your code.您的代码有几个问题。 The first one is with the type property you are passing to component.第一个是您传递给组件的类型属性。 The type isnt a number because you are formatting it to be a string, you should leave it unset or with the value category该类型不是数字,因为您将其格式化为字符串,您应该将其保留为未设置或使用值类别

<XAxis dataKey="dt" tickFormatter={(tick) => formatXAxis(tick)} type={'category'} />

The second one is with the way you are parsing the unix time with moment.第二个是您解析 unix 时间的方式。 You need first to tell moment that you are passing an unix format value on your function like this:您需要首先告诉您在 function 上传递 unix 格式值,如下所示:

const formatXAxis = (tickFormat) => {
  return moment.unix(tickFormat).format("DD/MM/YYYY");
};

Anyway I dont really like moment.js is a bit confusing and docs arent so clear also.无论如何,我不太喜欢 moment.js 有点混乱,文档也不是很清楚。 I recommend you using date fns for example and handling dates will be a way easier.我建议您使用 date fns 例如,处理日期会更容易。

I leave you a codesandbox with the full code.我给你留下了一个包含完整代码的代码框。

编辑嫩松iiqsp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM