fix(roi-editor):修复 ROI 编辑器中时间段选择器(TimePicker.RangePicker)因连续调用两次状态更新导致的清空问题。
Some checks failed
Python Test / test (push) Has been cancelled

- 新增 `updateWorkingHoursRange` 批量更新函数,将 start/end 作为原子操作同步更新
- 在 onChange 回调中添加 `Array.isArray(dates) && dates.length >= 2` 类型校验
- 避免 React 异步 setState 冲突导致 workingHoursList 意外重置
This commit is contained in:
2026-01-22 17:26:28 +08:00
parent cb46d12cfa
commit 3af7a0f805

View File

@@ -37,12 +37,38 @@ const ROIEditor: React.FC = () => {
const [selectedROI, setSelectedROI] = useState<ROI | null>(null); const [selectedROI, setSelectedROI] = useState<ROI | null>(null);
const [drawerVisible, setDrawerVisible] = useState(false); const [drawerVisible, setDrawerVisible] = useState(false);
const [form] = Form.useForm(); const [form] = Form.useForm();
const [workingHoursList, setWorkingHoursList] = useState<{start: dayjs.Dayjs | null, end: dayjs.Dayjs | null}[]>([]);
const [isDrawing, setIsDrawing] = useState(false); const [isDrawing, setIsDrawing] = useState(false);
const [tempPoints, setTempPoints] = useState<number[][]>([]); const [tempPoints, setTempPoints] = useState<number[][]>([]);
const [backgroundImage, setBackgroundImage] = useState<HTMLImageElement | null>(null); const [backgroundImage, setBackgroundImage] = useState<HTMLImageElement | null>(null);
const stageRef = useRef<any>(null); const stageRef = useRef<any>(null);
const addWorkingHours = () => {
setWorkingHoursList([...workingHoursList, { start: null, end: null }]);
};
const removeWorkingHours = (index: number) => {
const newList = workingHoursList.filter((_, i) => i !== index);
setWorkingHoursList(newList);
};
const updateWorkingHours = (index: number, field: 'start' | 'end', value: dayjs.Dayjs | null) => {
const newList = [...workingHoursList];
newList[index] = { ...newList[index], [field]: value };
setWorkingHoursList(newList);
};
const updateWorkingHoursRange = (index: number, start: dayjs.Dayjs | null, end: dayjs.Dayjs | null) => {
setWorkingHoursList(prev => {
const newList = [...prev];
if (newList[index]) {
newList[index] = { start, end };
}
return newList;
});
};
const fetchCameras = async () => { const fetchCameras = async () => {
try { try {
const res = await axios.get('/api/cameras?enabled_only=true'); const res = await axios.get('/api/cameras?enabled_only=true');
@@ -103,10 +129,12 @@ const ROIEditor: React.FC = () => {
const handleSaveROI = async (values: any) => { const handleSaveROI = async (values: any) => {
if (!selectedCamera || !selectedROI) return; if (!selectedCamera || !selectedROI) return;
try { try {
const workingHours = values.working_hours?.map((item: any) => ({ const workingHours = workingHoursList
start: [item.start.hour(), item.start.minute()], .filter(item => item.start && item.end)
end: [item.end.hour(), item.end.minute()], .map(item => ({
})); start: [item.start!.hour(), item.start!.minute()],
end: [item.end!.hour(), item.end!.minute()],
}));
await axios.put(`/api/camera/${selectedCamera}/roi/${selectedROI.id}`, { await axios.put(`/api/camera/${selectedCamera}/roi/${selectedROI.id}`, {
name: values.name, name: values.name,
@@ -119,6 +147,7 @@ const ROIEditor: React.FC = () => {
}); });
message.success('保存成功'); message.success('保存成功');
setDrawerVisible(false); setDrawerVisible(false);
setWorkingHoursList([]);
fetchROIs(); fetchROIs();
} catch (err: any) { } catch (err: any) {
message.error(`保存失败: ${err.response?.data?.detail || '未知错误'}`); message.error(`保存失败: ${err.response?.data?.detail || '未知错误'}`);
@@ -226,11 +255,11 @@ const ROIEditor: React.FC = () => {
threshold_sec: roi.threshold_sec, threshold_sec: roi.threshold_sec,
confirm_sec: roi.confirm_sec, confirm_sec: roi.confirm_sec,
enabled: roi.enabled, enabled: roi.enabled,
working_hours: roi.working_hours?.map((wh: WorkingHours) => ({
start: dayjs().hour(wh.start[0]).minute(wh.start[1]),
end: dayjs().hour(wh.end[0]).minute(wh.end[1]),
})),
}); });
setWorkingHoursList(roi.working_hours?.map((wh: WorkingHours) => ({
start: wh.start ? dayjs().hour(wh.start[0]).minute(wh.start[1]) : null,
end: wh.end ? dayjs().hour(wh.end[0]).minute(wh.end[1]) : null,
})) || []);
setDrawerVisible(true); setDrawerVisible(true);
}} }}
onMouseEnter={(e) => { onMouseEnter={(e) => {
@@ -387,11 +416,11 @@ const ROIEditor: React.FC = () => {
threshold_sec: roi.threshold_sec, threshold_sec: roi.threshold_sec,
confirm_sec: roi.confirm_sec, confirm_sec: roi.confirm_sec,
enabled: roi.enabled, enabled: roi.enabled,
working_hours: roi.working_hours?.map((wh: WorkingHours) => ({
start: dayjs().hour(wh.start[0]).minute(wh.start[1]),
end: dayjs().hour(wh.end[0]).minute(wh.end[1]),
})),
}); });
setWorkingHoursList(roi.working_hours?.map((wh: WorkingHours) => ({
start: wh.start ? dayjs().hour(wh.start[0]).minute(wh.start[1]) : null,
end: wh.end ? dayjs().hour(wh.end[0]).minute(wh.end[1]) : null,
})) || []);
setDrawerVisible(true); setDrawerVisible(true);
}} }}
> >
@@ -426,6 +455,7 @@ const ROIEditor: React.FC = () => {
onClose={() => { onClose={() => {
setDrawerVisible(false); setDrawerVisible(false);
setSelectedROI(null); setSelectedROI(null);
setWorkingHoursList([]);
}} }}
width={400} width={400}
> >
@@ -458,33 +488,35 @@ const ROIEditor: React.FC = () => {
<InputNumber min={5} style={{ width: '100%' }} /> <InputNumber min={5} style={{ width: '100%' }} />
</Form.Item> </Form.Item>
<Divider></Divider> <Divider></Divider>
<Form.List name="working_hours"> <div>
{(fields, { add, remove }) => ( {workingHoursList.map((item, index) => (
<div> <Space key={index} align="baseline" style={{ display: 'flex', marginBottom: 8 }}>
{fields.map((field, index) => ( <Form.Item label={index === 0 ? '时间段' : ''} style={{ marginBottom: 0 }}>
<Space key={field.key} align="baseline" style={{ display: 'flex', marginBottom: 8 }}> <TimePicker.RangePicker
<Form.Item format="HH:mm"
{...field} value={item.start && item.end ? [item.start, item.end] : null}
label={index === 0 ? '时间段' : ''} onChange={(dates) => {
style={{ marginBottom: 0 }} if (dates && Array.isArray(dates) && dates.length >= 2 && dates[0] && dates[1]) {
> updateWorkingHoursRange(index, dates[0], dates[1]);
<TimePicker.RangePicker format="HH:mm" /> } else {
</Form.Item> updateWorkingHoursRange(index, null, null);
<Button }
type="link" }}
danger />
onClick={() => remove(field.name)} </Form.Item>
> <Button
type="link"
</Button> danger
</Space> onClick={() => removeWorkingHours(index)}
))} >
<Button type="dashed" onClick={() => add({ start: null, end: null })} block>
</Button> </Button>
</div> </Space>
)} ))}
</Form.List> <Button type="dashed" onClick={addWorkingHours} block>
</Button>
</div>
<Form.Item style={{ fontSize: 12, color: '#999' }}> <Form.Item style={{ fontSize: 12, color: '#999' }}>
使 使
</Form.Item> </Form.Item>
@@ -501,6 +533,7 @@ const ROIEditor: React.FC = () => {
<Button onClick={() => { <Button onClick={() => {
setDrawerVisible(false); setDrawerVisible(false);
setSelectedROI(null); setSelectedROI(null);
setWorkingHoursList([]);
}}> }}>
</Button> </Button>