Skip to content

Immer 不可变数据实践

关于Immer 不可变数据实践,很多开发者只停留在 API 调用层面。本文试图从生产环境的角度,讨论实际中会遇到的问题和解决方案。

基本原理

关键在于理解核心逻辑:

javascript
import { create } from 'zustand'
import { persist, devtools } from 'zustand/middleware'

const useStore = create(
  devtools(persist(
    (set, get) => ({
      user: null,
      theme: 'light',
      notifications: [],
      setUser: (user) => set({ user }),
      toggleTheme: () => set(s => ({
        theme: s.theme === 'light' ? 'dark' : 'light'
      })),
      unreadCount: () => get().notifications.filter(n => !n.read).length
    }),
    { name: 'app-store' }
  ))
)

性能优化需要结合具体场景,不是所有情况都需要过度优化。

高级特性

我们可以通过以下方式来改进:

javascript
import { create } from 'zustand'
import { persist, devtools } from 'zustand/middleware'

const useStore = create(
  devtools(persist(
    (set, get) => ({
      user: null,
      theme: 'light',
      notifications: [],
      setUser: (user) => set({ user }),
      toggleTheme: () => set(s => ({
        theme: s.theme === 'light' ? 'dark' : 'light'
      })),
      unreadCount: () => get().notifications.filter(n => !n.read).length
    }),
    { name: 'app-store' }
  ))
)

这套方案已经在线上稳定运行了半年以上,经过了实际验证。

项目实践

先来看基本的实现方式:

javascript
import { create } from 'zustand'
import { persist, devtools } from 'zustand/middleware'

const useStore = create(
  devtools(persist(
    (set, get) => ({
      user: null,
      theme: 'light',
      notifications: [],
      setUser: (user) => set({ user }),
      toggleTheme: () => set(s => ({
        theme: s.theme === 'light' ? 'dark' : 'light'
      })),
      unreadCount: () => get().notifications.filter(n => !n.read).length
    }),
    { name: 'app-store' }
  ))
)

这段代码展示了基本的使用方式。实际项目中还需要考虑错误处理和边界条件。

最佳实践

在这个基础上,我们可以进一步优化:

javascript
import { create } from 'zustand'
import { persist, devtools } from 'zustand/middleware'

const useStore = create(
  devtools(persist(
    (set, get) => ({
      user: null,
      theme: 'light',
      notifications: [],
      setUser: (user) => set({ user }),
      toggleTheme: () => set(s => ({
        theme: s.theme === 'light' ? 'dark' : 'light'
      })),
      unreadCount: () => get().notifications.filter(n => !n.read).length
    }),
    { name: 'app-store' }
  ))
)

这种模式在大型项目中非常实用,能显著降低维护成本。

小结

  • 团队协作中约定和文档比技术本身更重要
  • 关注社区动态,技术方案需要持续迭代
  • 不要为了用新技术而用新技术
  • 代码示例仅供参考,需根据业务场景调整

MIT Licensed