※ 问题描述
两个隔离的组件「按钮组」和「折线图」,切换「按钮组」的选项,会触发「折线图」重新渲染。
import React, { useEffect, useState } from "react";
import { Line } from "@ant-design/charts";
const timeRangeOptions = [
{ label: "30分钟", value: 1800 },
{ label: "1小时", value: 3600 },
{ label: "6小时", value: 21600 },
{ label: "12小时", value: 43200 },
{ label: "1天", value: 86400 },
{ label: "7天", value: 604800 }
];
export interface AvailabilityLineProps {
data: Record<string, any>[];
}
export const AvailabilityLine: React.FC<AvailabilityLineProps> = ({data}) => {
return (
<Line data={data} height={200} xField={'timestamp'} yField={'Availability'} />
);
};
export default () => {
const [availabilityLineData, setAvailabilityLineData] = useState([]);
const changeTimeRange = (e: RadioChangeEvent) => {
setTimeRange(e.target.value);
};
return (
<Space direction="vertical" size="middle" className="w-100">
<SubTitle text="可用性">
<Radio.Group
options={timeRangeOptions}
onChange={changeTimeRange}
value={timeRange}
optionType="button"
buttonStyle="solid"
/>
</SubTitle>
<AvailabilityLine data={availabilityLineData} />
</Space>
);
};
如上述代码所示,未调用 setAvailabilityLineData
函数去修改「折线图」的数据,仅仅只是调用 changeTimeRange
就会触发「折线图」的渲染。
※ 解决办法
修改 AvailabilityLine
组件,使用 useMemo
缓存「折线图」的渲染,仅当 data
值发生改变才会重新渲染 。
import React, { useEffect, useState, useMemo } from "react";
import { Line } from "@ant-design/charts";
export const AvailabilityLine: React.FC<AvailabilityLineProps> = ({data}) => {
const component = useMemo(() => (<Line data={data} height={200} xField={'timestamp'} yField={'Availability'} />), [data]);
return component;
};
※ 参考资料
网友评论