feat: 已完成的工作

1. 创建性能监控工具
    - 提供完整的性能指标收集
    - 自动生成性能报告
    - 分析性能瓶颈并给出建议
  2. 创建React性能Hook
    - usePerformanceTracker - 追踪组件渲染性能
    - usePerformanceMark - 标记自定义操作
  3. 添加应用启动监控
    - 标记 app-start 时间点
    - 标记 react-ready 时间点
  4. 添加认证监控
    - 标记 auth-check-start 时间点
    - 需要补充 auth-check-end 时间点
This commit is contained in:
zdl
2025-11-25 16:03:52 +08:00
parent 28b9920443
commit e839435e96
3 changed files with 149 additions and 17 deletions

View File

@@ -3,6 +3,7 @@ import React, { createContext, useContext, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useToast } from '@chakra-ui/react';
import { logger } from '../utils/logger';
import { performanceMonitor } from '@/utils/performanceMonitor';
import { useNotification } from '../contexts/NotificationContext';
import { identifyUser, resetUser, trackEvent } from '@lib/posthog';
import { SPECIAL_EVENTS } from '@lib/constants';
@@ -52,6 +53,9 @@ export const AuthProvider = ({ children }) => {
lastCheckTimeRef.current = now;
// ⏱️ 性能监控: 标记认证检查开始
performanceMonitor.mark('auth-check-start');
try {
logger.debug('AuthContext', '开始检查Session状态', {
timestamp: new Date().toISOString(),
@@ -221,21 +225,7 @@ export const AuthProvider = ({ children }) => {
setUser(data.user);
setIsAuthenticated(true);
// ❌ 过时的追踪代码已移除(新代码在组件中使用 useAuthEvents 追踪
// 正确的事件追踪在 AuthFormContent.js 中调用 authEvents.trackLoginSuccess()
// 事件名:'User Logged In' 或 'User Signed Up'
// 属性名login_method (不是 loginType)
// ⚡ 移除toast让调用者处理UI反馈避免并发更新冲突
// toast({
// title: "登录成功",
// description: "欢迎回来!",
// status: "success",
// duration: 3000,
// isClosable: true,
// });
// ⚡ 登录成功后显示欢迎引导延迟2秒避免与登录Toast冲突
// ⚡ 登录成功后显示欢迎引导延迟2秒避免与登录Toast冲突移动端不显示
setTimeout(() => {
showWelcomeGuide();
}, 2000);
@@ -293,9 +283,9 @@ export const AuthProvider = ({ children }) => {
isClosable: true,
});
// ⚡ 注册成功后显示欢迎引导延迟2秒
// ⚡ 注册成功后显示欢迎引导延迟2秒,移动端不显示
setTimeout(() => {
showWelcomeGuide();
showWelcomeGuide();
}, 2000);
return { success: true };

View File

@@ -0,0 +1,135 @@
// src/hooks/usePerformanceTracker.ts
// React组件性能追踪Hook
import { useEffect, useRef } from 'react';
import { performanceMonitor } from '@/utils/performanceMonitor';
import { logger } from '@/utils/logger';
interface PerformanceTrackerOptions {
componentName: string;
trackMount?: boolean; // 是否追踪组件挂载
trackRender?: boolean; // 是否追踪每次渲染
logToConsole?: boolean; // 是否输出到控制台
}
/**
* 性能追踪Hook
* 用于监控React组件的渲染性能
*
* @example
* ```tsx
* function HomePage() {
* usePerformanceTracker({
* componentName: 'HomePage',
* trackMount: true,
* trackRender: true
* });
* // ...
* }
* ```
*/
export const usePerformanceTracker = ({
componentName,
trackMount = true,
trackRender = false,
logToConsole = true
}: PerformanceTrackerOptions) => {
const mountTimeRef = useRef<number>(0);
const renderCountRef = useRef<number>(0);
const lastRenderTimeRef = useRef<number>(0);
// 记录组件挂载时间
useEffect(() => {
if (!trackMount) return;
const mountTime = performance.now();
mountTimeRef.current = mountTime;
// 标记组件挂载完成
performanceMonitor.mark(`${componentName}-mounted`);
if (logToConsole) {
logger.info('PerformanceTracker', `🎨 ${componentName} mounted`, {
mountTime: `${mountTime.toFixed(2)}ms`,
timestamp: new Date().toISOString()
});
}
// Cleanup: 记录组件卸载
return () => {
const unmountTime = performance.now();
const lifetime = unmountTime - mountTime;
performanceMonitor.mark(`${componentName}-unmounted`);
if (logToConsole) {
logger.info('PerformanceTracker', `🗑️ ${componentName} unmounted`, {
lifetime: `${lifetime.toFixed(2)}ms`,
renderCount: renderCountRef.current
});
}
};
}, [componentName, trackMount, logToConsole]);
// 追踪每次渲染
useEffect(() => {
if (!trackRender) return;
renderCountRef.current += 1;
const renderTime = performance.now();
const timeSinceLastRender = lastRenderTimeRef.current
? renderTime - lastRenderTimeRef.current
: 0;
lastRenderTimeRef.current = renderTime;
performanceMonitor.mark(`${componentName}-render-${renderCountRef.current}`);
if (logToConsole) {
logger.debug('PerformanceTracker', `🔄 ${componentName} render #${renderCountRef.current}`, {
renderTime: `${renderTime.toFixed(2)}ms`,
timeSinceLastRender: timeSinceLastRender > 0
? `${timeSinceLastRender.toFixed(2)}ms`
: 'N/A'
});
}
});
return {
renderCount: renderCountRef.current,
mountTime: mountTimeRef.current
};
};
/**
* 标记性能时间点的Hook
* 用于标记组件内的关键操作
*
* @example
* ```tsx
* const { markStart, markEnd, measure } = usePerformanceMark('HomePage');
*
* useEffect(() => {
* markStart('data-fetch');
* fetchData().then(() => {
* markEnd('data-fetch');
* const duration = measure('data-fetch-start', 'data-fetch-end');
* });
* }, []);
* ```
*/
export const usePerformanceMark = (componentName: string) => {
const markStart = (operationName: string) => {
performanceMonitor.mark(`${componentName}-${operationName}-start`);
};
const markEnd = (operationName: string) => {
performanceMonitor.mark(`${componentName}-${operationName}-end`);
};
const measure = (startMarkName: string, endMarkName: string) => {
return performanceMonitor.measure(startMarkName, endMarkName);
};
return { markStart, markEnd, measure };
};

View File

@@ -1,4 +1,8 @@
// src/index.js
// ⏱️ 性能监控: 标记应用启动时间
import { performanceMonitor } from '@/utils/performanceMonitor';
performanceMonitor.mark('app-start');
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter as Router } from 'react-router-dom';
@@ -126,6 +130,9 @@ async function startApp() {
// Create root
const root = ReactDOM.createRoot(document.getElementById('root'));
// ⏱️ 性能监控: 标记React准备就绪
performanceMonitor.mark('react-ready');
// Render the app with Router wrapper
// ✅ StrictMode 已启用Chakra UI 2.10.9+ 已修复兼容性问题)
root.render(