{post.title}
{post.content}
目录
一、深度性能优化
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
九、推荐学习路径
十、扩展工具链
处理大数据量列表时,使用 react-window
实现虚拟滚动:
npm install react-window
import { FixedSizeList as List } from 'react-window';
const BigList = ({ data }) => (
{({ index, style }) => (
Row {data[index]}
)}
);
// 使用
i)} />
// 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 (
{result && Result: {result}}
);
}
// 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 (
{children}
);
}
export const useAuth = () => useContext(AuthContext);
// 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));
}
};
function DynamicForm({ fields, onSubmit }) {
return (
);
}
// 使用
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 (
{dropdown.isOpen && (
{dropdown.options.map((opt) => (
- dropdown.setSelected(opt)}>
{opt}
))}
)}
);
}
// 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 (
Server-Side Rendered Data
{JSON.stringify(data, null, 2)}
);
}
// 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 (
{post.title}
{post.content}
);
}
npm install framer-motion
import { motion, AnimatePresence } from 'framer-motion';
function Modal({ isOpen, onClose }) {
return (
{isOpen && (
Modal Content
)}
);
}
2. 拖拽交互实现
import { useDrag } from 'react-dnd';
function DraggableItem({ id, text }) {
const [{ isDragging }, drag] = useDrag(() => ({
type: 'ITEM',
item: { id },
collect: (monitor) => ({
isDragging: !!monitor.isDragging(),
}),
}));
return (
{text}
);
}
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',
},
};
使用 Profiler 分析组件渲染性能
查看组件 Hooks 依赖关系图
追踪不必要的渲染原因
// 初始化
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);
}
// 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 |