데이터 생성으로 recharts 바 차트를 사용하여 목록 DTO

0

질문

이 DTO 체에서 생성되는 Rest API 를 사용하여 타이프 라이터:

export interface BillingSummaryDTO {
    paid?: number,
    outstanding?: number,
    pastDue?: number,
    cancelled?: number,
    createdAt?: Moment | null,
}

export async function getBillingSummary(): Promise<AxiosResponse<BillingSummaryDTO[]>> {
  return await axios.get<BillingSummaryDTO[]>(
      `${baseUrl}/management/billing/summary`
  );
}

예 차트:

import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
} from "recharts";
import {Box} from "@material-ui/core";

const data = [
  {
    name: "Jan",
    Chargebacks: 4000,
    Transactions: 2400,
    USD: 2400,
  },
  {
    name: "Feb",
    Chargebacks: 3000,
    Transactions: 1398,
    USD: 2210,
  },
  {
    name: "Mar",
    Chargebacks: 2000,
    Transactions: 9800,
    USD: 2290,
  },
  {
    name: "Apr",
    Chargebacks: 2780,
    Transactions: 3908,
    USD: 2000,
  },
  {
    name: "May",
    Chargebacks: 1890,
    Transactions: 4800,
    USD: 2181,
  },
  {
    name: "Jun",
    Chargebacks: 2390,
    Transactions: 3800,
    USD: 2500,
  },
  {
    name: "Jul",
    Chargebacks: 3490,
    Transactions: 4300,
    USD: 2100,
  },
  {
    name: "Aug",
    Chargebacks: 3490,
    Transactions: 4300,
    USD: 2100,
  },
  {
    name: "Sep",
    Chargebacks: 3490,
    Transactions: 4300,
    USD: 2100,
  },
];

const useStyles = makeStyles((theme) =>
  createStyles({
    root: {
      flexGrow: 1,
    },
    paper: {
      padding: theme.spacing(2),
      textAlign: "center",
      color: theme.palette.text.secondary,
    },
  })
);

const usePaperStyles = makeStyles((theme) =>
  createStyles({
    root: {
      display: "flex",
      flexWrap: "wrap",
      "& > *": {
        margin: theme.spacing(1),
        width: theme.spacing(16),
        height: theme.spacing(16),
      },
    },
  })
);

const useTimelineStyles = makeStyles((theme) => ({
  paper: {
    padding: "6px 16px",
  },
  secondaryTail: {
    backgroundColor: theme.palette.secondary.main,
  },
}));

export default function Billing() {
  const [click, setClick] = useState(false);
  const closeMobileMenu = () => setClick(false);
  const classes = useStyles();
  const classesPaper = usePaperStyles();
  const classesTimeline = useTimelineStyles();

  return (
    <>
      <Grid container justifyContent="center" alignItems="center">
        <Grid item xs={11}>
          {/*Padding on the top*/}
          <Box m="5rem" />
        </Grid>

        <Grid item xs={12} >
          <h4 className="chart-label">Invoices Summary</h4>
          <BarChart
            width={1000}
            height={300}
            data={data}
            margin={{
              top: 5,
              right: 30,
              left: 20,
              bottom: 5,
            }}
            barSize={30}
          >
            <XAxis
              dataKey="name"
              scale="point"
              padding={{ left: 10, right: 10 }}
            />
            <YAxis />
            <Tooltip />
            <Legend />
            <CartesianGrid strokeDasharray="3 3" />
            <Bar
              dataKey="Transactions"
              fill="#8884d8"
              background={{ fill: "#eee" }}
            />
          </BarChart>
        </Grid>
      </Grid>
    </>
  );
}

어떻게 데이터를 사용할 수 있습니다 BillingSummaryDTO[] 를 생성하는가?

1

최고의 응답

2

를 만드는 함수는 지도 위에 BillingSummaryDTO[]로 변환 데이터 모델(로에서 볼 수 있는 변수 data)지정한에 대한 소비에 의하여 <BarChart/> 유효한 접근 방식이다.

export interface BarChartDataModel {
  name: string,
  Chargebacks: number,
  Transactions: number,
  USD: number,
}

const data : BarChartDataModel []

이 데이터를 사용되는 것에 <BarChart/>


<BarChart
            data={data}
            // ....
          >
         // ...
 </BarChart>

이러한 기능에 따라 map reduce 접근 방식에서 약간의 도움으로 JS 날짜 관리 라이브러리 같은 momentjs

4 단계 솔루션

  1. 정렬 모든 청구서 시간적으로(가장 오래된 법안을 처음)을 쉽게지도를 줄이 나중
  2. 물통 지폐에 의해 버킷으로 불리는'yearwise-킷'
  3. 물통을 청구에서 각 yearwise-bucket 버킷으로 불리는'monthwise-양동'
  4. 을 줄이 모든 청구서 각 monthwise-양동이를 객체는 다음의 BarChartDataModel 인터페이스입니다. 개체의 모음을 다음 BarChartDataModel 인터페이스 data 우리는 우리의 <BarChart/> 구성 요소
  5. 소비체 이 컬렉션은 우리의 인 <BarChart/> 구성 요소

코드 같은 것:

export interface BillingSummaryDTO {
    paid?: number,
    outstanding?: number,
    pastDue?: number,
    cancelled?: number,
    createdAt?: Moment | null,
}

export interface BarChartDataModel {
  name: string,
  Chargebacks: number,
  Transactions: number,
  USD: number,
}

export async function getBillingSummary(): Promise<AxiosResponse<BillingSummaryDTO[]>> {
  const response = await axios.get<BillingSummaryDTO[]>(
      `${baseUrl}/management/billing/summary`
  );
  // STEP 1 : Chronological ordering. Oldest bills will show first
  const chronologicallyOrdered = response.sort((a:BillingSummaryDTO,b:BillingSummaryDTO)=> a.createdAt - b.createdAt )

  // STEP 2 : Bucket by year
  const groupByYear = chronologicallyOrdered.reduce((yearwiseBills : any, bill:BillingSummaryDTO, currIdx:number)) => 
     {
        const year = moment(bill.createdAt).year().toString()
        if(!yearwiseBills[year]){ 
          yearwiseBills[year] = []
        } 
        yearwiseBills[year].push(bill)
        return yearwiseBills
     }
  ,{})

  // STEP 3 : In each yearwise bucket -> bucket by month
  const groupByMonth = Object.keys(groupByYear).map((year, yearwiseBills) => yearwiseBills.reduce((monthwiseBills: any, bill:BillingSummaryDTO, currIdx:number)) => 
     {
        const moment = moment(bill.createdAt).month().toString()
        if(!yearAcc[month]){ 
          monthwiseBills[month] = []
        } 
        monthwiseBills[month].push(bill)
        return monthwiseBills
     }
  ,{}) );

 // STEP 4 : Reduce all bills in a monthwise bucket into a monthlyReport object and store all monthlyReport objects in an monthlyReportArray
 const monthlyReportArray:BarChartDataModel[] = Object.keys(groupByMonth).map((year, yearwiseBills) => 
   Object.keys(bills).map((month, monthwiseBills) => monthwiseBills.reduce((monthlyReport:BarChartDataModel,bill:BillingSummaryDTO) => {
    if(bill.cancelled){
      monthlyReport.Chargebacks++
    }else{
      monthlyReport.Transactions++,
      monthlyReport.USD += bill.paid
    }
    return monthlyReport
  },{
    name : moment(month, 'M').format('MMM')
    Transactions : 0,
    USD : 0,
    Chargebacks:0
   } )
 )


 // STEP 5 : Consume this as the "data" for the "<BarChart/>" component
 return monthlyReportArray
}
 

나는 버킷화에 의해 올해 처음 버킷팅에 달하는 대신 버킷팅 달기 때문에 우리가 원하지 않을 결합하는 월간 보고서의"말할 수 있습 1997"및"수 있습 1998 년으로"다만"도"우리의 차트입니다. 우리는 것이 그들이 원하는 별도의

2021-11-24 05:49:15

나는 여러 오류가 있습니다. 당신은 이것이야 적절한 솔루션?
Peter Penzov

당신은 오류? 방법 지도-을 줄이 완벽하다,그래서 논리 스틱입니다. 구문에 문제가 발생할 수 있습니다(주로 유형-오류 확인).
Ankit Sanghvi

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................