在Chart.js中格式化标签,数据表单axios

ltqd579y  于 2022-11-06  发布在  Chart.js
关注(0)|答案(2)|浏览(145)

我正在使用chart.js来创建折线图。我想显示日期和月份数据,如8月25日,7月16日。我不知道如何更改从API下载的数据格式。请帮助。这是我的代码,谢谢提示
在Chart.JS中有没有一种正确的方法来格式化数据标签的日期?

import axios from 'axios';
import { useParams } from 'react-router-dom';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';

import { Line } from 'react-chartjs-2';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

const rate = axios.create({
  baseURL: 'http://api.nbp.pl/api/exchangerates/rates/a/',
});

const Chart = () => {
  const [post, setPost] = useState();
  const { id } = useParams();

  useEffect(() => {
    async function getPost() {
      const response = await rate.get(`/${id}/last/10/?format=json`);
      setPost(response.data);
    }
    getPost();
  }, [id]);

  const data = {
    type: 'line',
    labels: post?.rates?.map((x) => x.effectiveDate),
    datasets: [
      {
        label: `Ostatnie 10 odczytów`,
        data: post?.rates?.map((y) => y.mid),
        lineTension: 0.1,
        backgroundColor: 'rgba(15, 174, 150)',
        borderColor: 'rgba(15, 174, 150)',
        gridLines: 'false',
        borderCapStyle: 'butt',
        borderDash: [],
        borderDashOffset: 0.0,
        borderJoinStyle: 'miter',
        pointBorderColor: 'rgba(15, 174, 150)',
        pointBackgroundColor: '#fff',
        pointBorderWidth: 1,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: 'rgba(15, 174, 150)',
        pointHoverBorderColor: 'rgba(220,220,220,1)',
        pointHoverBorderWidth: 2,
        pointRadius: 1,
        pointHitRadius: 10,
      },
    ],
    options: {
      responsive: true,
    },
  };

  return (
    <div
      style={{
        width: '800px',
        height: '800px',
        margin: '0px auto',
        paddingTop: '500px',
      }}
    >
      <Line data={data} />
    </div>
  );
};

export default Chart;
vltsax25

vltsax251#

欢迎Veronica!如果您不想使用第三方包,我建议您使用Date类型和Intl.DateTimeFormat对象。一旦您转换为Date,您就可以构建所需的字符串。

post?.rates?.map(x => {
    date = new Date(x.effectiveDate);

    return new Intl.DateTimeFormat('en-US', {
        month: 'short',
        day: 'numeric',
    }).format(date);
});
hvvq6cgz

hvvq6cgz2#

你好,我想你可以用moment或dayjs(同样的东西和moment,因为它的建议dayjs已经过时了)来表示这个,比如post?.rates?.map((x)=〉moment(x.effectiveDate).format('你想要的格式))

相关问题