React 前端开发

难度等级:⭐⭐⭐ 前置知识:编程语言基础、Web 基础 后续衔接:架构设计、工程化

学习路径


一、React 核心概念

1.1 JSX 语法

JSX 是 JavaScript 的语法扩展,允许在 JS 中编写类似 HTML 的结构。

核心要点

代码示例

interface UserCardProps {
  name: string
  age: number
  isActive: boolean
}

const UserCard: React.FC<UserCardProps> = ({ name, age, isActive }) => {
  return (
    <div className={`card ${isActive ? 'active' : ''}`}>
      <h2>{name}</h2>
      <p>年龄: {age}</p>
      {isActive && <span>在线</span>}
    </div>
  )
}

关联知识点:TypeScript、组件定义

1.2 组件与 Props

组件是 React 的基本构建单元,接收 props 作为输入,返回 React 元素。

核心要点

代码示例

interface ButtonProps {
  variant?: 'primary' | 'secondary' | 'danger'
  size?: 'sm' | 'md' | 'lg'
  disabled?: boolean
  onClick: () => void
  children: React.ReactNode
}

const Button: React.FC<ButtonProps> = ({
  variant = 'primary',
  size = 'md',
  disabled = false,
  onClick,
  children,
}) => {
  return (
    <button
      className={`btn btn-${variant} btn-${size}`}
      disabled={disabled}
      onClick={onClick}
    >
      {children}
    </button>
  )
}

关联知识点:单向数据流、组件设计

1.3 虚拟 DOM 与协调算法

React 使用虚拟 DOM 来优化渲染性能。

核心要点

关联知识点:渲染性能、Fiber 架构


二、Hooks 详解

2.1 useState 和 useReducer

状态管理的基础 Hooks。

核心要点

代码示例

// useState 示例
const [count, setCount] = useState(0)
const increment = () => setCount(prev => prev + 1)

// useReducer 示例
interface State {
  items: Item[]
  loading: boolean
  error: string | null
}

type Action =
  | { type: 'FETCH_START' }
  | { type: 'FETCH_SUCCESS'; payload: Item[] }
  | { type: 'FETCH_ERROR'; payload: string }

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'FETCH_START':
      return { ...state, loading: true, error: null }
    case 'FETCH_SUCCESS':
      return { ...state, loading: false, items: action.payload }
    case 'FETCH_ERROR':
      return { ...state, loading: false, error: action.payload }
    default:
      return state
  }
}

const [state, dispatch] = useReducer(reducer, {
  items: [],
  loading: false,
  error: null,
})

关联知识点:状态管理、Redux 模式

2.2 useEffect

处理副作用的 Hook。

核心要点

代码示例

function useDocumentTitle(title: string) {
  useEffect(() => {
    document.title = title
    return () => {
      document.title = '默认标题' // 清理
    }
  }, [title])
}

function ChatRoom({ roomId }: { roomId: string }) {
  useEffect(() => {
    const connection = createConnection(roomId)
    connection.connect()
    return () => connection.disconnect() // 清理
  }, [roomId]) // roomId 变化时重新连接
}

关联知识点:副作用管理、生命周期

2.3 useContext

跨组件共享数据。

核心要点

代码示例

interface Theme {
  colors: {
    primary: string
    background: string
  }
  toggle: () => void
}

const ThemeContext = createContext<Theme | undefined>(undefined)

function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [isDark, setIsDark] = useState(false)
  const theme: Theme = useMemo(() => ({
    colors: isDark ? darkColors : lightColors,
    toggle: () => setIsDark(prev => !prev),
  }), [isDark])

  return (
    <ThemeContext.Provider value={theme}>
      {children}
    </ThemeContext.Provider>
  )
}

function ThemedButton() {
  const theme = useContext(ThemeContext)
  if (!theme) throw new Error('useContext must be inside ThemeProvider')
  return <button style={theme.colors} onClick={theme.toggle}>切换主题</button>
}

关联知识点:状态共享、性能优化

2.4 useMemo 和 useCallback

性能优化 Hooks。

核心要点

代码示例

function ProductList({ products, onSelect }: { products: Product[], onSelect: (id: number) => void }) {
  // 缓存过滤结果
  const availableProducts = useMemo(
    () => products.filter(p => p.available),
    [products]
  )

  // 缓存函数引用
  const handleSelect = useCallback(
    (id: number) => {
      console.log('Selected:', id)
      onSelect(id)
    },
    [onSelect]
  )

  return (
    <ul>
      {availableProducts.map(product => (
        <ProductItem
          key={product.id}
          product={product}
          onSelect={handleSelect}
        />
      ))}
    </ul>
  )
}

关联知识点:渲染优化、缓存策略

2.5 自定义 Hooks

提取和复用组件逻辑。

核心要点

代码示例

function useLocalStorage<T>(key: string, initialValue: T) {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      const item = window.localStorage.getItem(key)
      return item ? JSON.parse(item) : initialValue
    } catch {
      return initialValue
    }
  })

  const setValue = (value: T | ((val: T) => T)) => {
    const valueToStore = value instanceof Function ? value(storedValue) : value
    setStoredValue(valueToStore)
    window.localStorage.setItem(key, JSON.stringify(valueToStore))
  }

  return [storedValue, setValue] as const
}

// 使用
const [theme, setTheme] = useLocalStorage('theme', 'light')

关联知识点:逻辑复用、本地存储


三、状态管理

3.1 Context API + useReducer

React 内置的轻量级状态管理方案。

核心要点

关联知识点:Context、useReducer

3.2 Redux Toolkit

官方推荐的 Redux 实现方式。

核心要点

代码示例

import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'

interface User {
  id: number
  name: string
}

interface UserState {
  data: User | null
  loading: boolean
  error: string | null
}

export const fetchUser = createAsyncThunk<User, number>(
  'user/fetch',
  async (id) => {
    const response = await api.getUser(id)
    return response.data
  }
)

const userSlice = createSlice({
  name: 'user',
  initialState: { data: null, loading: false, error: null } as UserState,
  reducers: {
    clearUser: (state) => {
      state.data = null
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchUser.pending, (state) => {
        state.loading = true
      })
      .addCase(fetchUser.fulfilled, (state, action: PayloadAction<User>) => {
        state.loading = false
        state.data = action.payload
      })
      .addCase(fetchUser.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message ?? 'Unknown error'
      })
  },
})

export const { clearUser } = userSlice.actions
export default userSlice.reducer

关联知识点:Redux、异步处理

3.3 Zustand

轻量级状态管理库,API 简洁。

核心要点

代码示例

import { create } from 'zustand'

interface CartStore {
  items: CartItem[]
  total: number
  addItem: (item: CartItem) => void
  removeItem: (id: number) => void
  clear: () => void
}

const useCartStore = create<CartStore>((set) => ({
  items: [],
  total: 0,
  addItem: (item) => set((state) => ({
    items: [...state.items, item],
    total: state.total + item.price,
  })),
  removeItem: (id) => set((state) => {
    const item = state.items.find(i => i.id === id)
    return {
      items: state.items.filter(i => i.id !== id),
      total: state.total - (item?.price ?? 0),
    }
  }),
  clear: () => set({ items: [], total: 0 }),
}))

// 使用
const items = useCartStore((state) => state.items) // 精确订阅

关联知识点:状态管理、精确订阅


四、React Router

4.1 路由基础

React Router 是 React 生态中的路由解决方案。

核心要点

代码示例

import { BrowserRouter, Routes, Route, Link, Outlet } from 'react-router-dom'

function Layout() {
  return (
    <div>
      <nav>
        <Link to="/">首页</Link>
        <Link to="/about">关于</Link>
      </nav>
      <Outlet /> {/* 子路由渲染位置 */}
    </div>
  )
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="about" element={<About />} />
          <Route path="users/:id" element={<UserDetail />} />
          <Route path="*" element={<NotFound />} />
        </Route>
      </Routes>
    </BrowserRouter>
  )
}

关联知识点:单页应用、懒加载


五、前端设计模式在 React 中的应用

5.1 Observer(观察者模式)

应用场景

代码示例

// 简单事件总线
class EventEmitter {
  private listeners = new Map<string, Function[]>()

  on(event: string, fn: Function) {
    const fns = this.listeners.get(event) || []
    fns.push(fn)
    this.listeners.set(event, fns)
  }

  emit(event: string, ...args: any[]) {
    this.listeners.get(event)?.forEach(fn => fn(...args))
  }
}

export const eventBus = new EventEmitter()

关联知识点:事件系统、状态订阅

5.2 Factory(工厂模式)

应用场景

代码示例

const componentMap: Record<string, React.ComponentType<any>> = {
  input: InputField,
  select: SelectField,
  textarea: TextAreaField,
}

function FieldFactory({ type, ...props }: { type: string } & FieldProps) {
  const Component = componentMap[type]
  if (!Component) return null
  return <Component {...props} />
}

关联知识点:动态组件、代码生成

5.3 Strategy(策略模式)

应用场景

代码示例

type SortStrategy = (a: Product, b: Product) => number

const sortStrategies: Record<string, SortStrategy> = {
  priceAsc: (a, b) => a.price - b.price,
  priceDesc: (a, b) => b.price - a.price,
  name: (a, b) => a.name.localeCompare(b.name),
  date: (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
}

function ProductList({ products, sortBy }: { products: Product[], sortBy: string }) {
  const sorted = useMemo(() => {
    const strategy = sortStrategies[sortBy]
    return strategy ? [...products].sort(strategy) : products
  }, [products, sortBy])

  return <ul>{sorted.map(p => <li key={p.id}>{p.name}</li>)}</ul>
}

关联知识点:算法切换、 useMemo

5.4 Singleton(单例模式)

应用场景

关联知识点:全局实例

5.5 Decorator(装饰器模式)

应用场景

代码示例

// HOC 示例:添加 loading 状态
function withLoading<P extends object>(
  Component: React.ComponentType<P>
): React.FC<P & { isLoading: boolean }> {
  return function WithLoadingComponent({ isLoading, ...props }) {
    if (isLoading) return <div>Loading...</div>
    return <Component {...(props as P)} />
  }
}

// 使用
const ProductListWithLoading = withLoading(ProductList)
<ProductListWithLoading products={products} isLoading={loading} />

关联知识点:HOC、代码复用

5.6 Adapter(适配器模式)

应用场景

代码示例

interface APIUser {
  user_name: string
  user_age: number
}

interface User {
  name: string
  age: number
}

function adaptUser(apiUser: APIUser): User {
  return {
    name: apiUser.user_name,
    age: apiUser.user_age,
  }
}

function UserCard({ apiUser }: { apiUser: APIUser }) {
  const user = useMemo(() => adaptUser(apiUser), [apiUser])
  return <div>{user.name} - {user.age}</div>
}

关联知识点:数据转换、接口统一

5.7 Proxy(代理模式)

应用场景

关联知识点:缓存、权限控制

5.8 Facade(外观模式)

应用场景

代码示例

// API 外观
export const api = {
  users: {
    list: (params: QueryParams) => http.get('/users', { params }),
    get: (id: number) => http.get(`/users/${id}`),
    create: (data: CreateUserDTO) => http.post('/users', data),
    update: (id: number, data: UpdateUserDTO) => http.put(`/users/${id}`, data),
    delete: (id: number) => http.delete(`/users/${id}`),
  }
}

关联知识点:API 设计、封装

5.9 Command(命令模式)

应用场景

关联知识点:撤销重做、操作队列

5.10 Builder(建造者模式)

应用场景

代码示例

class QueryBuilder {
  private filters: Filter[] = []
  private sortField = ''
  private sortOrder: 'asc' | 'desc' = 'asc'
  private page = 1
  private pageSize = 10

  where(field: string, op: string, value: any) {
    this.filters.push({ field, op, value })
    return this
  }

  orderBy(field: string, order: 'asc' | 'desc' = 'asc') {
    this.sortField = field
    this.sortOrder = order
    return this
  }

  paginate(page: number, size: number) {
    this.page = page
    this.pageSize = size
    return this
  }

  build(): QueryParams {
    return {
      filters: this.filters,
      sort: { field: this.sortField, order: this.sortOrder },
      page: this.page,
      pageSize: this.pageSize,
    }
  }
}

const query = new QueryBuilder()
  .where('status', '=', 'active')
  .orderBy('created_at', 'desc')
  .paginate(1, 20)
  .build()

关联知识点:链式调用、复杂对象构建

5.11 HOC(高阶组件模式)

应用场景

关联知识点:组件增强、逻辑复用

5.12 Render Props 模式

应用场景

代码示例

interface MouseProps {
  x: number
  y: number
}

class MouseTracker extends React.Component<{ children: (props: MouseProps) => React.ReactNode }> {
  state: MouseProps = { x: 0, y: 0 }

  handleMouseMove = (e: React.MouseEvent) => {
    this.setState({ x: e.clientX, y: e.clientY })
  }

  render() {
    return (
      <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
        {this.props.children(this.state)}
      </div>
    )
  }
}

// 使用
<MouseTracker>
  {({ x, y }) => <p>鼠标位置: {x}, {y}</p>}
</MouseTracker>

关联知识点:逻辑复用、渲染定制

5.13 Prototype(原型模式)

通过克隆现有对象创建新对象,避免重复初始化。

应用场景

代码示例

// 深拷贝组件配置
function cloneConfig<T extends object>(config: T): T {
  return structuredClone(config)
}

const baseFormConfig = {
  fields: [
    { type: 'input', label: 'Name', required: true },
    { type: 'select', label: 'Role', options: ['admin', 'user'] },
  ],
  submitUrl: '/api/form',
}

const editFormConfig = cloneConfig(baseFormConfig)
editFormConfig.fields.push({ type: 'textarea', label: 'Notes' })

关联知识点:对象克隆、配置管理

5.14 Bridge(桥接模式)

将抽象部分与实现部分分离,使它们可以独立变化。

应用场景

代码示例

interface ChartRenderer {
  render(data: ChartData): JSX.Element
}

class EChartsRenderer implements ChartRenderer {
  render(data: ChartData) { /* ECharts 实现 */ }
}

class ChartJsRenderer implements ChartRenderer {
  render(data: ChartData) { /* Chart.js 实现 */ }
}

// 桥接:根据配置选择实现
const Renderer = useECharts ? EChartsRenderer : ChartJsRenderer

关联知识点:接口抽象、多端适配

5.15 Composite(组合模式)

将对象组合成树形结构,统一处理单个对象和组合对象。

应用场景

代码示例

interface MenuItem {
  label: string
  children?: MenuItem[]
  action?: () => void
}

function Menu({ items }: { items: MenuItem[] }) {
  return (
    <ul>
      {items.map((item, i) => (
        <li key={i}>
          <button onClick={item.action}>{item.label}</button>
          {item.children && <Menu items={item.children} />} {/* 递归组合 */}
        </li>
      ))}
    </ul>
  )
}

关联知识点:递归组件、树形结构

5.16 Flyweight(享元模式)

共享细粒度对象,减少内存占用。

应用场景

代码示例

// 图标享元池
const iconPool = new Map<string, React.ReactElement>()

function getIcon(name: string): React.ReactElement {
  if (!iconPool.has(name)) {
    iconPool.set(name, createSVGIcon(name))
  }
  return React.cloneElement(iconPool.get(name)!)
}

// 避免重复创建相同图标
const UserIcon = getIcon('user')
const AdminIcon = getIcon('admin')

关联知识点:内存优化、对象池

5.17 Iterator(迭代器模式)

提供顺序访问集合元素的方法,不暴露内部结构。

应用场景

代码示例

// 分页迭代器
async function* paginatedIterator<T>(fetchFn: (page: number) => Promise<T[]>) {
  let page = 1
  while (true) {
    const items = await fetchFn(page)
    if (items.length === 0) break
    for (const item of items) yield item
    page++
  }
}

// 使用
const iterator = paginatedIterator((page) => fetch(`/users?page=${page}`))
for await (const user of iterator) {
  console.log(user.name)
}

关联知识点:生成器、懒加载

5.18 Mediator(中介者模式)

用中介对象封装一系列对象交互,降低耦合度。

应用场景

代码示例

class FormMediator {
  private components = new Map<string, any>()
  
  register(name: string, component: any) {
    this.components.set(name, component)
  }
  
  notify(sender: string, event: string) {
    if (sender === 'submit' && event === 'click') {
      const isValid = Array.from(this.components.values())
        .every(c => c.validate?.() ?? true)
      if (isValid) this.components.get('api')?.submit()
    }
  }
}

关联知识点:解耦、事件协调

5.19 Memento(备忘录模式)

捕获和恢复对象内部状态,不破坏封装性。

应用场景

代码示例

class EditorMemento {
  private history: string[] = []
  private currentIndex = -1
  
  save(state: string) {
    this.history = this.history.slice(0, this.currentIndex + 1)
    this.history.push(state)
    this.currentIndex++
  }
  
  undo(): string | null {
    if (this.currentIndex > 0) {
      this.currentIndex--
      return this.history[this.currentIndex]
    }
    return null
  }
  
  redo(): string | null {
    if (this.currentIndex < this.history.length - 1) {
      this.currentIndex++
      return this.history[this.currentIndex]
    }
    return null
  }
}

关联知识点:撤销重做、状态快照

5.20 State(状态模式)

对象内部状态改变时改变其行为。

应用场景

代码示例

interface OrderState {
  pay: () => void
  ship: () => void
  cancel: () => void
}

function createPendingState(): OrderState {
  return {
    pay: () => { /* → PaidState */ },
    ship: () => { throw new Error('Cannot ship pending order') },
    cancel: () => { /* → CancelledState */ },
  }
}

function createPaidState(): OrderState {
  return {
    pay: () => { throw new Error('Already paid') },
    ship: () => { /* → ShippedState */ },
    cancel: () => { /* → RefundedState */ },
  }
}

关联知识点:状态机、业务流

5.21 Interpreter(解释器模式)

定义语言文法表示,并定义解释器处理它。

应用场景

代码示例

interface Expression {
  interpret(context: Record<string, any>): boolean
}

class AndExpression implements Expression {
  constructor(private left: Expression, private right: Expression) {}
  interpret(ctx) { return this.left.interpret(ctx) && this.right.interpret(ctx) }
}

class OrExpression implements Expression {
  constructor(private left: Expression, private right: Expression) {}
  interpret(ctx) { return this.left.interpret(ctx) || this.right.interpret(ctx) }
}

class RoleExpression implements Expression {
  constructor(private role: string) {}
  interpret(ctx) { return ctx.roles.includes(this.role) }
}

// 解析 "admin && (read || write)"
const expr = new AndExpression(
  new RoleExpression('admin'),
  new OrExpression(new RoleExpression('read'), new RoleExpression('write'))
)
expr.interpret({ roles: ['admin', 'read'] }) // true

关联知识点:语法解析、规则引擎

5.22 Visitor(访问者模式)

在不改变对象结构的前提下,定义作用于对象各元素的新操作。

应用场景

代码示例

interface ComponentNode {
  type: string
  props?: Record<string, any>
  children?: ComponentNode[]
}

interface Visitor {
  visitComponent(node: ComponentNode): void
}

function traverse(node: ComponentNode, visitor: Visitor) {
  visitor.visitComponent(node)
  node.children?.forEach(child => traverse(child, visitor))
}

// 具体访问者:统计组件数量
class ComponentCounter implements Visitor {
  count = 0
  visitComponent() { this.count++ }
}

关联知识点:AST、组件分析


六、前端架构模式

6.1 MVC(Model-View-Controller)

将应用分为模型(数据)、视图(UI)、控制器(业务逻辑)。

核心要点

关联知识点:架构模式、后端 MVC

6.2 MVP(Model-View-Presenter)

MVC 的演进,Presenter 完全隔离 View 和 Model。

核心要点

关联知识点:解耦、测试驱动

6.3 Flux / Redux 模式

单向数据流架构,适合复杂状态管理。

核心要点

关联知识点:状态管理、单向数据流

6.4 组件化架构

React 的核心架构思想。

核心要点

关联知识点:组件设计、组合优于继承


七、组件通信模式

6.1 Props 传递

父子组件通信的标准方式。

核心要点

关联知识点:单向数据流

6.2 Context 共享

跨层级组件通信。

核心要点

关联知识点:Context API、性能优化

6.3 状态管理库

全局状态共享。

核心要点

关联知识点:Redux、Zustand


八、性能优化

7.1 渲染优化

核心要点

关联知识点:缓存策略、性能分析

7.2 代码分割

核心要点

代码示例

const Home = React.lazy(() => import('./pages/Home'))
const Dashboard = React.lazy(() => import('./pages/Dashboard'))

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/dashboard" element={<Dashboard />} />
      </Routes>
    </Suspense>
  )
}

关联知识点:懒加载、Suspense

7.3 列表优化

核心要点

关联知识点:虚拟滚动、大数据处理


八、工程化

8.1 Vite 和 Create React App

核心要点

关联知识点:构建工具、开发体验

8.2 Next.js

Next.js 是 React 的全栈框架。

核心要点

关联知识点:SSR、SSG、全栈框架

8.3 TypeScript 集成

React 与 TypeScript 集成优秀。

核心要点

关联知识点:类型安全、开发效率


九、测试

9.1 单元测试

使用 Jest + React Testing Library。

核心要点

关联知识点:测试策略、质量保证

9.2 E2E 测试

使用 Cypress 或 Playwright。

核心要点

关联知识点:自动化测试、CI/CD


十、生态系统

10.1 React Query / SWR

服务端状态管理。

核心要点

关联知识点:数据获取、缓存策略

10.2 UI 组件库

关联知识点:组件库、开发效率


十一、与其他框架对比

React vs Vue vs Angular

特性 React 18 Vue 3 Angular
学习曲线
响应式 手动(useState) 自动追踪(Proxy) 自动(Zone.js)
模板 JSX HTML 模板 HTML 模板
状态管理 Redux/Zustand Pinia NgRx
路由 React Router Vue Router Router
类型支持 优秀 优秀 优秀
适用场景 大型项目、灵活需求 中小型项目、快速开发 企业级大型应用

关联知识点:技术选型、框架对比


十二、最佳实践

12.1 代码组织

12.2 性能优化

12.3 安全注意事项

12.4 常见陷阱

关联知识点:代码质量、性能、安全