深色模式
Valtio Proxy 状态管理这个话题社区讨论了很多次,但随着版本迭代,很多结论需要更新。本文基于最新版本重新梳理。
入门指南
先来看基本的实现方式:
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' }
))
)注意边界条件处理,这在生产环境中至关重要。
小结
- 代码示例仅供参考,需根据业务场景调整
- Valtio Proxy 状态管理不是银弹,需要根据项目规模和技术栈选择
- 理解底层原理比记住 API 更重要