目录
一、深度性能优化
1. 列表渲染优化(虚拟列表)
2. 使用 Web Workers 处理 CPU 密集型任务
二、复杂状态管理场景
1. 全局状态分层(Context + useReducer)
2. 异步状态管理中间件(Redux Thunk)
三、高级组件模式扩展
1. 控制反转(Inversion of Control)
2. Headless 组件模式
四、服务端渲染与静态生成(Next.js 集成)
1. 基础 SSR 实现
2. 静态生成(SSG)
五、动画与交互增强
1. 使用 Framer Motion 实现复杂动画
六、工程化最佳实践
1. 项目目录结构规范
七、调试与错误排查
1. React DevTools 高级用法
2. 错误日志收集(Sentry 集成)
八、微前端架构实践
1. 使用 Module Federation
九、推荐学习路径
十、扩展工具链
一、深度性能优化
1. 列表渲染优化(虚拟列表)
处理大数据量列表时,使用 react-window
实现虚拟滚动:
npm install react-window
import { FixedSizeList as List } from 'react-window';
const BigList = ({ data }) => (
<List
height={400}
itemCount={data.length}
itemSize={50}
width={300}
>
{({ index, style }) => (
<div style={style}>Row {data[index]}</div>
)}
</List>
);
// 使用
<BigList data={Array(1000).fill().map((_, i) => i)} />
2. 使用 Web Workers 处理 CPU 密集型任务
// worker.js
self.onmessage = (e) => {
const result = heavyCalculation(e.data);
self.postMessage(result);
};
// 主线程使用
function App() {
const [result, setResult] = useState(null);
const workerRef = useRef(null);
useEffect(() => {
workerRef.current = new Worker('worker.js');
workerRef.current.onmessage = (e) => setResult(e.data);
return () => workerRef.current.terminate();
}, []);
const handleCalculate = () => {
workerRef.current.postMessage(inputData);
};
return (
<div>
<button onClick={handleCalculate}>Start Calculation</button>
{result && <div>Result: {result}</div>}
</div>
);
}
二、复杂状态管理场景
1. 全局状态分层(Context + useReducer)
// contexts/authContext.js
const AuthContext = React.createContext();
export function AuthProvider({ children }) {
const [state, dispatch] = useReducer(authReducer, initialState);
const login = async (credentials) => {
dispatch({ type: 'LOGIN_REQUEST' });
try {
const user = await api.login(credentials);
dispatch({ type: 'LOGIN_SUCCESS', payload: user });
} catch (error) {
dispatch({ type: 'LOGIN_FAILURE', payload: error });
}
};
return (
<AuthContext.Provider value={{ ...state, login }}>
{children}
</AuthContext.Provider>
);
}
export const useAuth = () => useContext(AuthContext);
2. 异步状态管理中间件(Redux Thunk)
// store.js
import { configureStore } from '@reduxjs/toolkit';
import { fetchUser } from './userSlice';
const store = configureStore({
reducer: userReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(thunkMiddleware),
});
// userSlice.js
export const fetchUser = (userId) => async (dispatch) => {
dispatch(userLoading());
try {
const user = await api.getUser(userId);
dispatch(userSuccess(user));
} catch (error) {
dispatch(userFailure(error));
}
};
三、高级组件模式扩展
1. 控制反转(Inversion of Control)
function DynamicForm({ fields, onSubmit }) {
return (
<form onSubmit={onSubmit}>
{fields.map((FieldComponent, index) => (
<FieldComponent key={index} />
))}
<button type="submit">Submit</button>
</form>
);
}
// 使用
<DynamicForm
fields={[TextInput, DatePicker, Dropdown]}
onSubmit={handleSubmit}
/>
2. Headless 组件模式
function useDropdown(options) {
const [isOpen, setIsOpen] = useState(false);
const [selected, setSelected] = useState(null);
const toggle = () => setIsOpen(!isOpen);
return {
isOpen,
selected,
toggle,
options,
setSelected,
};
}
// 使用
function CustomDropdown() {
const dropdown = useDropdown(['Option 1', 'Option 2']);
return (
<div className="dropdown">
<button onClick={dropdown.toggle}>
{dropdown.selected || 'Select...'}
</button>
{dropdown.isOpen && (
<ul>
{dropdown.options.map((opt) => (
<li key={opt} onClick={() => dropdown.setSelected(opt)}>
{opt}
</li>
))}
</ul>
)}
</div>
);
}
四、服务端渲染与静态生成(Next.js 集成)
1. 基础 SSR 实现
// pages/index.js
export async function getServerSideProps() {
const data = await fetch('https://api.example.com/data').then(res => res.json());
return { props: { data } };
}
export default function HomePage({ data }) {
return (
<div>
<h1>Server-Side Rendered Data</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
2. 静态生成(SSG)
// pages/posts/[id].js
export async function getStaticPaths() {
const posts = await fetch('https://api.example.com/posts')
.then(res => res.json());
const paths = posts.map(post => ({
params: { id: post.id.toString() }
}));
return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
const post = await fetch(`https://api.example.com/posts/${params.id}`)
.then(res => res.json());
return { props: { post } };
}
export default function Post({ post }) {
return (
<article>
<h1>{post.title}</h1>
<div>{post.content}</div>
</article>
);
}
五、动画与交互增强
1. 使用 Framer Motion 实现复杂动画
npm install framer-motion
import { motion, AnimatePresence } from 'framer-motion';
function Modal({ isOpen, onClose }) {
return (
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="modal"
>
<motion.div
initial={{ y: 50 }}
animate={{ y: 0 }}
>
<button onClick={onClose}>Close</button>
Modal Content
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
}
2. 拖拽交互实现
import { useDrag } from 'react-dnd';
function DraggableItem({ id, text }) {
const [{ isDragging }, drag] = useDrag(() => ({
type: 'ITEM',
item: { id },
collect: (monitor) => ({
isDragging: !!monitor.isDragging(),
}),
}));
return (
<div
ref={drag}
style={{ opacity: isDragging ? 0.5 : 1 }}
className="draggable"
>
{text}
</div>
);
}
六、工程化最佳实践
1. 项目目录结构规范
src/
├── components/ # 通用组件
├── features/ # 功能模块
│ └── auth/
│ ├── components/ # 模块专用组件
│ ├── hooks/ # 模块自定义 Hooks
│ └── slices/ # Redux Toolkit slices
├── lib/ # 工具函数/第三方集成
├── pages/ # 页面组件(Next.js 路由)
└── stores/ # 全局状态管理
2. 自定义 ESLint 配置
// .eslintrc.js
module.exports = {
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
],
rules: {
'react/prop-types': 'off',
'no-unused-vars': 'warn',
'react-hooks/exhaustive-deps': 'error',
},
};
七、调试与错误排查
1. React DevTools 高级用法
-
使用 Profiler 分析组件渲染性能
-
查看组件 Hooks 依赖关系图
-
追踪不必要的渲染原因
2. 错误日志收集(Sentry 集成)
// 初始化
import * as Sentry from '@sentry/react';
Sentry.init({
dsn: 'YOUR_DSN',
integrations: [new Sentry.BrowserTracing()],
tracesSampleRate: 1.0,
});
// 错误边界自动捕获
const ErrorBoundary = Sentry.ErrorBoundary;
// 手动捕获
try {
riskyOperation();
} catch (error) {
Sentry.captureException(error);
}
八、微前端架构实践
1. 使用 Module Federation
// webpack.config.js (Host)
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'host',
remotes: {
remoteApp: 'remoteApp@http://localhost:3001/remoteEntry.js',
},
}),
],
};
// 动态加载远程组件
const RemoteComponent = React.lazy(() => import('remoteApp/Button'));
九、推荐学习路径
-
实战项目:电商后台管理系统、实时协作工具
-
源码学习:阅读 React 核心算法 reconciler 源码
-
性能大师:深入研究 React 的 Fiber 架构与调度机制
-
架构演进:从单体应用到微前端架构的迁移策略
十、扩展工具链
类别 | 推荐工具 |
---|---|
状态管理 | Zustand, Jotai |
表单处理 | React Hook Form |
数据请求 | SWR, React Query |
静态站点 | Gatsby |
移动端 | React Native |
桌面端 | Electron + React |