From 710baf61d4e8d3c2b6b3323d8468018953db9eed Mon Sep 17 00:00:00 2001 From: zdl <3489966805@qq.com> Date: Thu, 30 Oct 2025 18:39:16 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20NotificationTestToo?= =?UTF-8?q?l=20=E8=BF=9D=E5=8F=8D=20React=20Hooks=20=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修复控制台错误 "React has detected a change in the order of Hooks" **问题原因** NotificationTestTool 组件违反了 React Hooks 规则: - Hooks 必须在每次渲染时以相同的顺序调用 - 不能在条件语句之后调用 Hooks **错误模式(Before):** ```javascript const NotificationTestTool = () => { const { isOpen, onToggle } = useDisclosure(); // Hook #1 const { addNotification, ... } = useNotification(); // Hooks #2-8 const [testCount, setTestCount] = useState(0); // Hook #9 // ... 更多 Hooks // ❌ 错误:在调用所有 Hooks 之后才检查环境 if (process.env.NODE_ENV !== 'development') { return null; } // ... }; ``` 当环境变化时,Hook 调用数量变化导致 React 检测到顺序不一致。 **修复方案(After):** ```javascript const NotificationTestTool = () => { // ✅ 正确:在任何 Hooks 调用之前就进行早期返回 if (process.env.NODE_ENV !== 'development') { return null; } // 现在所有 Hooks 都在条件检查之后 const { isOpen, onToggle } = useDisclosure(); const { addNotification, ... } = useNotification(); // ... }; ``` **React Hooks 规则** 1. 只在顶层调用 Hooks - 不要在循环、条件或嵌套函数中调用 2. Hooks 调用顺序必须在每次渲染时保持一致 3. 条件性的早期返回必须在所有 Hooks 调用之前 **修复内容** - 将环境检查移到组件顶部(line 34-36) - 删除底部重复的环境检查(原 line 126-128) - 确保所有 Hooks 在条件检查之后调用 **测试结果** - ✅ 编译成功 - ✅ 不再显示 "change in the order of Hooks" 错误 - ✅ 开发环境正常显示测试工具 - ✅ 生产环境正确隐藏测试工具 **文件修改** - src/components/NotificationTestTool/index.js - 移动环境检查到顶部 - 删除重复的环境检查 --- src/components/NotificationTestTool/index.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/components/NotificationTestTool/index.js b/src/components/NotificationTestTool/index.js index ab8c89ec..51f09b64 100644 --- a/src/components/NotificationTestTool/index.js +++ b/src/components/NotificationTestTool/index.js @@ -30,6 +30,11 @@ import { SOCKET_TYPE } from '../../services/socket'; import { NOTIFICATION_TYPES, PRIORITY_LEVELS } from '../../constants/notificationTypes'; const NotificationTestTool = () => { + // 只在开发环境显示 - 必须在所有 Hooks 调用之前检查 + if (process.env.NODE_ENV !== 'development') { + return null; + } + const { isOpen, onToggle } = useDisclosure(); const { addNotification, soundEnabled, toggleSound, isConnected, clearAllNotifications, notifications, browserPermission, requestBrowserPermission } = useNotification(); const [testCount, setTestCount] = useState(0); @@ -122,11 +127,6 @@ const NotificationTestTool = () => { await requestBrowserPermission(); }; - // 只在开发环境显示 - if (process.env.NODE_ENV !== 'development') { - return null; - } - // 公告通知测试数据 const testAnnouncement = () => { addNotification({