From 36b929a9d2e4a5660168259833881b0708c48b46 Mon Sep 17 00:00:00 2001 From: hamster1963 <1410514192@qq.com> Date: Mon, 14 Oct 2024 17:29:55 +0800 Subject: [PATCH] perf: chart --- .../(main)/ClientComponents/NetworkChart.tsx | 120 +++++++++--------- 1 file changed, 57 insertions(+), 63 deletions(-) diff --git a/app/[locale]/(main)/ClientComponents/NetworkChart.tsx b/app/[locale]/(main)/ClientComponents/NetworkChart.tsx index 1ed4158..f20c09f 100644 --- a/app/[locale]/(main)/ClientComponents/NetworkChart.tsx +++ b/app/[locale]/(main)/ClientComponents/NetworkChart.tsx @@ -30,6 +30,7 @@ import { useRouter } from "next/navigation"; import * as React from "react"; import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts"; import useSWR from "swr"; +import { useMemo, useCallback } from 'react'; interface ResultItem { created_at: number; @@ -138,7 +139,7 @@ export function NetworkChartClient({ server_id }: { server_id: number }) { ); } -export function NetworkChart({ +export const NetworkChart = React.memo(function NetworkChart({ chartDataKey, chartConfig, chartData, @@ -159,18 +160,59 @@ export function NetworkChart({ const [activeChart, setActiveChart] = React.useState(defaultChart); - const handleButtonClick = (chart: string) => { - if (chart === activeChart) { - setActiveChart(defaultChart); - } else { - setActiveChart(chart); - } - }; + const handleButtonClick = useCallback((chart: string) => { + setActiveChart(prev => prev === chart ? defaultChart : chart); + }, [defaultChart]); - const getColorByIndex = (chart: string) => { + const getColorByIndex = useCallback((chart: string) => { const index = chartDataKey.indexOf(chart); return `hsl(var(--chart-${(index % 10) + 1}))`; - }; + }, [chartDataKey]); + + const chartButtons = useMemo(() => ( + chartDataKey.map((key) => ( + + )) + ), [chartDataKey, activeChart, chartData, handleButtonClick]); + + const chartLines = useMemo(() => { + if (activeChart !== defaultChart) { + return ( + + ); + } + return chartDataKey.map((key) => ( + + )); + }, [activeChart, defaultChart, chartDataKey, getColorByIndex]); return ( @@ -190,26 +232,7 @@ export function NetworkChart({
- {chartDataKey.map((key) => { - return ( - - ); - })} + {chartButtons}
@@ -219,15 +242,8 @@ export function NetworkChart({ > } /> )} - {activeChart !== defaultChart && ( - - )} - {activeChart === defaultChart && - chartDataKey.map((key) => ( - - ))} + {chartLines}
); -} +});