reactjs 我的ChartJS日期无法从Coinranking API中正确显示

oknrviil  于 2023-02-12  发布在  React
关注(0)|答案(2)|浏览(113)

下面是我的代码,显示一个加密货币的图表,以及它在一段时间内的价格变化。我还包括了jsx文件和. env文件
日本证券交易所:

import React from 'react';
import { Line } from 'react-chartjs-2';
import { Col, Row, Typography } from 'antd';

const { Title } = Typography;

const LineChart = ({ coinHistory, currentPrice, coinName }) => {
  const coinPrice = [];
  const coinTimestamp = [];

  for (let i = 0; i < coinHistory?.data?.history?.length; i += 1) {
    coinPrice.push(coinHistory?.data?.history[i].price);
  }

  for (let i = 0; i < coinHistory?.data?.history?.length; i += 1) {
    coinTimestamp.push(new Date(coinHistory?.data?.history[i].timestamp).toLocaleDateString());
  }
  const data = {
    labels: coinTimestamp,
    datasets: [
      {
        label: 'Price In USD',
        data: coinPrice,
        fill: false,
        backgroundColor: '#0071bd',
        borderColor: '#0071bd',
      },
    ],
  };

  const options = {
    scales: {
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
          },
        },
      ],
    },
  };

  return (
    <>
      <Row className="chart-header">
        <Title level={2} className="chart-title">{coinName} Price Chart </Title>
        <Col className="price-container">
          <Title level={5} className="price-change">Change: {coinHistory?.data?.change}%</Title>
          <Title level={5} className="current-price">Current {coinName} Price: $ {currentPrice}</Title>
        </Col>
      </Row>
      <Line data={data} options={options} />
    </>
  );
};

export default LineChart;

. js文件:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const cryptoApiHeaders = {
  'x-rapidapi-host': process.env.REACT_APP_CRYPTO_RAPIDAPI_HOST,
  'x-rapidapi-key': process.env.REACT_APP_RAPIDAPI_KEY,
};
const createRequest = (url) => ({ url, headers: cryptoApiHeaders });

export const cryptoApi = createApi({
  reducerPath: 'cryptoApi',
  baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_CRYPTO_API_URL }),
  endpoints: (builder) => ({
    getCryptos: builder.query({
      query: (count) => createRequest(`/coins?limit=${count}`),
    }),

    getCryptoDetails: builder.query({
      query: (coinId) => createRequest(`/coin/${coinId}`),
    }),

    getCryptoHistory: builder.query({
      query: ({ coinId, timeperiod }) => createRequest(`coin/${coinId}/history?timeperiod=${timeperiod}`),
    }),

    getExchanges: builder.query({
      query: () => createRequest('/exchanges'),
    }),
  }),
});

export const {
  useGetCryptosQuery,
  useGetCryptoDetailsQuery,
  useGetExchangesQuery,
  useGetCryptoHistoryQuery,
} = cryptoApi;

.环境:

REACT_APP_RAPIDAPI_KEY =  'my_key'
REACT_APP_CRYPTO_API_URL = 'https://coinranking1.p.rapidapi.com'
REACT_APP_NEWS_API_URL = 'https://bing-news-search1.p.rapidapi.com'
REACT_APP_NEWS_RAPIDAPI_HOST = 'bing-news-search1.p.rapidapi.com'
REACT_APP_CRYPTO_RAPIDAPI_HOST ='coinranking1.p.rapidapi.com'

ESLINT_NO_DEV_ERRORS=true

当我运行React代码时,图表上显示的日期是19/1/1970,我不知道为什么实际日期没有显示在图表中,其他数据显示了出来,所以我相信关键是好的。

bksxznpy

bksxznpy1#

如果您使用ChartJS V.3 -〉
首先你应该添加一个日期适配器,如果你使用date-fns或moment,每个例子都有一个适配器:

import {
        Chart as ChartJS,
        LinearScale,
        PointElement,
        LineElement,
        Tooltip,
        Filler,
        TimeScale,
    } from 'chart.js'
    
    import "chartjs-adapter-moment"
    
    ChartJS.register(
        LinearScale,
        TimeScale,
        PointElement,
        Filler,
LineElement,
    Tooltip,
)

然后,您必须在xAxes选项中添加时间格式:

x: {
                    type: 'time',
                    time: {
                        unit: "day",
                        displayFormats: {
                            day: "MMM DD YYYY" // or whatever you want to display your date
                        }
                    },
}

如果使用ChartJS V2:
不要安装适配器,这不是必须的,但添加在您的秤选项:

xAxes: [
                    {
                        // stacked: true,
                        type: 'time',
                        time: {
                            unit: 'day',
                            displayFormats: {
                                day: 'MMM DD YYYY'
                            }
                        },
                    },
                ],
ltskdhd1

ltskdhd12#

你只需要做一个小的改变,同时把日期推到时间戳数组。

coinTimeStamp.push(new Date(coinHistory.data.history[i].timestamp*1000).toLocaleDateString());

您需要将时间戳乘以1000。

相关问题