fix: 修复 NotificationTestTool 违反 React Hooks 规则

修复控制台错误 "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
  - 移动环境检查到顶部
  - 删除重复的环境检查
This commit is contained in:
zdl
2025-10-30 18:39:16 +08:00
parent d57db02c15
commit cbf421af16

View File

@@ -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({