Atom 状态管理
本文档系统性介绍 Atom 状态管理的概念、理论基础和实践应用
# 📖 目录
# 核心概念
# 什么是 Atom?
Atom(原子)是状态管理中的最小可订阅单元,代表一个独立的、不可再分的状态片段。
词源:ἄτομος (希腊语) → 不可分割的 → 状态的最小单位
1
# 三个核心特征
| 特征 | 说明 | 价值 |
|---|---|---|
| 🔹 独立性 | 每个 Atom 管理独立的状态片段 | 避免状态耦合,提高可维护性 |
| 🔄 可订阅 | 状态变化时自动通知订阅者 | 实现响应式更新 |
| 🌐 全局访问 | 可在应用任何地方读写 | 避免 props drilling |
# 学术定义与理论来源
# 理论基础
Atom 概念源于 响应式编程(Reactive Programming) 范式,融合了以下理论:
┌─────────────────────────────────────────┐
│ 响应式编程核心理论 │
├─────────────────────────────────────────┤
│ • Observable Pattern (观察者模式) │
│ • Dependency Tracking (依赖追踪) │
│ • Fine-grained Reactivity (细粒度响应) │
│ • Functional Reactive Programming (FRP) │
└─────────────────────────────────────────┘
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 主流实现
# 1. Recoil (Facebook/Meta, 2020)
- 官网:https://recoiljs.org/
- 定义:"An atom represents a piece of state. Atoms can be read from and written to from any component."
- 特点:为 React 设计的细粒度状态管理
# 2. Jotai (Daishi Kato, 2020)
- 官网:https://jotai.org/
- 定义:"Primitive and flexible state management for React"
- 特点:更轻量级,底层 API
# 3. MobX Observable
- 官网:https://mobx.js.org/
- 特点:可观察对象,自动追踪依赖
# 4. Solid.js Signals
- 细粒度响应式系统
- 性能优化极致
# 核心特性
# 五大核心属性
| 属性 | 英文 | 说明 | 实现方式 |
|---|---|---|---|
| 原子性 | Atomicity | 不可再分的最小单元 | 每个 atom 独立管理状态 |
| 可观察性 | Observability | 状态变化可被追踪 | subscribes 订阅列表 |
| 响应性 | Reactivity | 自动传播更新 | setAtomValue 触发订阅 |
| 可组合性 | Composability | 可派生计算状态 | createSelector |
| 值语义 | Value Semantics | 不可变数据 | deepClone 默认值 |
# 架构设计
// Atom 内部结构
interface AtomItem {
type: AtomType.atom, // 类型标识
value: any, // 当前状态值
subscribes: (() => void)[], // 订阅者列表
destory: () => void // 生命周期管理
}
// 全局状态管理器
class RootAtom {
atoms: Record<string, AtomItem> = {}; // 所有 atom 的注册表
setAtomValue(key, value) // 更新状态并通知订阅者
subscribe(key, callback) // 订阅状态变化
destoryAtom(key) // 销毁 atom
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 实现原理
# 工作流程
1. 创建阶段
createAtom({ key, defaultValue })
↓
生成唯一 key
↓
返回 { getValue, setValue, destroy }
2. 使用阶段
组件调用 getValue()
↓
initAtom() - 懒初始化
↓
注册到 rootAtom.atoms
↓
返回当前值
3. 更新阶段
组件调用 setValue(newValue)
↓
浅比较检测变化
↓
更新 atom.value
↓
触发所有 subscribes
↓
组件重新渲染
4. 销毁阶段
destroy()
↓
检查订阅者是否清理
↓
从 rootAtom 移除
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 关键机制
# 1. 懒初始化
function initAtom() {
if (!rootAtom.atoms[key]) {
rootAtom.atoms[key] = {
type: AtomType.atom,
value: deepClone(defaultValue), // 深拷贝避免污染
subscribes: [],
destory: () => rootAtom.destoryAtom(key),
};
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 2. 浅比较优化
setAtomValue(k: string, v: any) {
const curAtom = this.atoms[k];
// 引用相等直接返回
if (curAtom.value === v) return;
// 对象浅比较
if (isObject(curAtom.value) && isObject(v)) {
const newValue = v;
const curValue = this.atoms[k].value;
// 所有属性都相等则跳过更新
if (Object.keys(newValue).every(vk => newValue[vk] === curValue[vk])) {
return;
}
// Partial 更新(保留未变化的属性)
curAtom.value = Object.assign({}, curAtom.value, v);
} else {
curAtom.value = v;
}
// 通知订阅者
curAtom.subscribes.forEach(setter => setter());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 3. 依赖追踪
// 收集依赖的 atom keys
private usingAtomCollectors: string[][] = [];
getAtomValue(key: string) {
this.addUsingAtom(key); // 记录当前 atom 被使用
return this.atoms[key].value;
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# API 文档
# createAtom<T>
创建一个新的状态原子。
function createAtom<T>({
key?: string, // 可选的唯一标识(会自动添加 ID)
defaultValue: T // 初始值
}): {
getValue: () => T,
setValue: (value: T | Partial<T>) => void,
destroy: () => void
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
返回值:
getValue()- 获取当前状态值setValue(value)- 设置新状态值(支持 Partial 更新)destroy()- 销毁 atom(清理资源)
# createSelector<T>
创建派生状态(类似计算属性)。
function createSelector<T>(
get: (v?: any) => T, // 计算函数
originkey?: string // 可选的标识
): {
getValue: () => T,
destroy: () => void
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# observeSync<T>
同步监听状态变化。
function observeSync<T>(
selector: (preValue: any) => T, // 选择器函数
callback: (preValue: T | undefined, curValue: T) => void,
name?: string, // 调试名称
isEqual?: typeof shallowEqual // 自定义比较函数
): () => void // 返回取消订阅函数
1
2
3
4
5
6
2
3
4
5
6
# observeAsync<T>
异步监听状态变化(在 requestAnimationFrame 中执行)。
function observeAsync<T>(
selector: (preValue: any) => T,
callback: (preValue: T | undefined, curValue: T) => void,
name?: string,
isEqual?: typeof shallowEqual
): () => void
1
2
3
4
5
6
2
3
4
5
6
# AtomClass<T>
封装了 atom 和 observe 的便捷类。
class AtomClass<T> {
constructor(name: string, defaultValue: T)
getValue: () => T
setValue: (value: Partial<T>) => void
observeSync: typeof observeSync
observeAsync: typeof observeAsync
destroy: () => void
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 使用场景
# ✅ 适合使用 Atom 的场景
| 场景 | 说明 | 示例 |
|---|---|---|
| 🌐 跨组件状态共享 | 多个不相关组件需要访问同一状态 | 用户信息、主题配置 |
| 🎮 复杂业务逻辑 | 状态逻辑复杂,需要解耦 | 挂件状态、游戏状态 |
| 🔔 订阅通知机制 | 需要在状态变化时执行副作用 | 数据同步、日志上报 |
| 📊 派生计算状态 | 需要基于多个状态计算新值 | 购物车总价、过滤列表 |
| 🎯 细粒度更新 | 避免不必要的组件重渲染 | 大型列表、实时数据 |
# ❌ 不适合使用 Atom 的场景
| 场景 | 说明 | 替代方案 |
|---|---|---|
| 🏠 组件内部状态 | 只在单个组件内使用 | useState、useReducer |
| 👨👦 父子组件通信 | 简单的单向数据流 | props 传递 |
| 🔀 一次性状态传递 | 不需要持久化和订阅 | 函数参数、Context |
| 📝 表单临时状态 | 表单输入的临时值 | 受控组件、表单库 |
# 代码示例
# 基础使用
import { createAtom } from 'src/lib/atom';
// 1. 创建 atom
export const userAtom = createAtom({
key: 'user',
defaultValue: {
id: 0,
name: '',
isLogin: false
}
});
// 2. 读取状态
const user = userAtom.getValue();
console.log(user.name);
// 3. 更新状态(Partial 更新)
userAtom.setValue({
isLogin: true,
name: 'John'
});
// 4. 销毁(组件卸载时)
userAtom.destroy();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 复杂业务场景
// 挂件状态管理(真实案例)
export const pendantAtom = createAtom({
key: 'god',
defaultValue: {
// 主面板状态
isH5Ready: false,
h5UIReady: false,
panelHomeVisible: false,
// UI 状态
showGod: true,
showFinger: false,
showCoinFloat: true,
// 业务数据
drawCoinCount: 0,
aniDrawCoinCount: 0,
extraCoin: 0,
// 动画状态
isCoinAnimating: false,
isSlideRewardAnimating: false,
// 实验配置
experiment: PendantGodAb.Unknown,
}
});
// 使用示例
class GodPendant {
init() {
// 初始化完成
pendantAtom.setValue({ isH5Ready: true });
}
showPanel() {
const state = pendantAtom.getValue();
if (!state.isH5Ready) return;
pendantAtom.setValue({
panelHomeVisible: true,
showFinger: false
});
}
drawCoin() {
const state = pendantAtom.getValue();
pendantAtom.setValue({
drawCoinCount: state.drawCoinCount + 1,
isCoinAnimating: true
});
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 派生状态(Selector)
import { createSelector } from 'src/lib/atom';
// 基于 pendantAtom 派生计算状态
export const pendantSelector = createSelector(() => {
const state = pendantAtom.getValue();
return {
// 是否可以转圈
canDrawCoin: state.isH5Ready && !state.isCoinAnimating,
// 是否显示面板
shouldShowPanel: state.panelHomeVisible && state.h5UIReady,
// 总获得金币数
totalCoins: state.drawCoinCount * 10 + state.extraCoin
};
});
// 使用
const derived = pendantSelector.getValue();
if (derived.canDrawCoin) {
// 执行转圈逻辑
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 状态监听(Observer)
import { observeSync, observeAsync } from 'src/lib/atom';
// 同步监听
const unsubscribe = observeSync(
() => pendantAtom.getValue().showGod,
(prevValue, curValue) => {
console.log(`小财神显示状态: ${prevValue} -> ${curValue}`);
if (curValue) {
// 显示动画
showGodAnimation();
} else {
// 隐藏动画
hideGodAnimation();
}
},
'god-visibility' // 调试名称
);
// 异步监听(性能优化)
const unsubscribeAsync = observeAsync(
() => pendantAtom.getValue().drawCoinCount,
(prevCount, curCount) => {
// 在 requestAnimationFrame 中执行
updateCoinDisplay(curCount);
}
);
// 清理订阅
unsubscribe();
unsubscribeAsync();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 使用 AtomClass(推荐)
import { AtomClass } from 'src/lib/atom';
export class GodAtom extends AtomClass {
constructor() {
super('God', {
isReady: false,
coinCount: 0
});
// 自动管理订阅生命周期
this.observeSync(
() => this.getValue().coinCount,
(prev, cur) => {
console.log(`金币变化: ${prev} -> ${cur}`);
}
);
}
// 业务方法
addCoin(amount: number) {
const state = this.getValue();
this.setValue({
coinCount: state.coinCount + amount
});
}
// 统一清理
cleanup() {
this.destroy(); // 自动清理所有订阅
}
}
// 使用
const godAtom = new GodAtom();
godAtom.addCoin(10);
godAtom.cleanup();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 与其他方案对比
# 对比表格
| 维度 | Atom | Redux | MobX | Context API | useState |
|---|---|---|---|---|---|
| 状态粒度 | 细粒度 ⭐⭐⭐⭐⭐ | 粗粒度 ⭐⭐ | 细粒度 ⭐⭐⭐⭐⭐ | 中等 ⭐⭐⭐ | 局部 ⭐ |
| 性能 | 高 ⭐⭐⭐⭐⭐ | 中 ⭐⭐⭐ | 高 ⭐⭐⭐⭐⭐ | 低 ⭐⭐ | 高 ⭐⭐⭐⭐ |
| 学习曲线 | 低 ⭐⭐ | 高 ⭐⭐⭐⭐⭐ | 中 ⭐⭐⭐ | 低 ⭐⭐ | 低 ⭐ |
| 可调试性 | 中 ⭐⭐⭐ | 高 ⭐⭐⭐⭐⭐ | 中 ⭐⭐⭐ | 低 ⭐⭐ | 中 ⭐⭐⭐ |
| 代码量 | 少 ⭐⭐ | 多 ⭐⭐⭐⭐⭐ | 少 ⭐⭐ | 少 ⭐⭐ | 少 ⭐ |
| 适用规模 | 中小型 | 大型 | 中大型 | 小型 | 任意 |
# 架构对比
# Redux(单一状态树)
┌────────────────────┐
│ Single Store │
│ ┌──────────────┐ │
│ │Global State │ │
│ │ ├─user │ │
│ │ ├─cart │ │
│ │ └─ui │ │
│ └──────────────┘ │
│ ↓ │
│ Reducers │
│ ↓ │
│ Components │
└────────────────────┘
优势:
• 可预测的状态流
• 时间旅行调试
• 中心化管理
劣势:
• 样板代码多
• 性能开销大
• 全量更新组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Atom-based(原子化状态)
┌──┐ ┌──┐ ┌──┐ ┌──┐
│A1│ │A2│ │A3│ │A4│
└──┘ └──┘ └──┘ └──┘
↓ ↓ ↓ ↓
组件按需订阅任意 Atom
只更新依赖该 Atom 的组件
优势:
• 细粒度更新
• 按需订阅
• 避免过度渲染
• 代码分离
劣势:
• 缺少全局视图
• 复杂依赖难调试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 选型建议
项目规模 推荐方案
─────────────────────────────
小型项目 Atom / Context
(<10 个状态)
中型项目 Atom / MobX
(10-50 个状态)
大型项目 Redux + Redux Toolkit
(>50 个状态)
性能敏感 Atom / Jotai
(移动端、动画)
团队熟悉度 根据实际情况选择
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 最佳实践
# 1. 命名规范
// ✅ 好的命名
export const userAtom = createAtom({ key: 'user', ... });
export const cartAtom = createAtom({ key: 'cart', ... });
export const themeAtom = createAtom({ key: 'theme', ... });
// ❌ 避免的命名
export const atom1 = createAtom({ key: 'a', ... });
export const state = createAtom({ key: 's', ... });
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 2. 状态设计
// ✅ 合理的状态粒度
export const pendantAtom = createAtom({
key: 'pendant',
defaultValue: {
// 相关的状态放在一起
isReady: false,
isVisible: false,
position: { x: 0, y: 0 }
}
});
// ❌ 过度拆分
export const isReadyAtom = createAtom({ key: 'isReady', defaultValue: false });
export const isVisibleAtom = createAtom({ key: 'isVisible', defaultValue: false });
export const positionXAtom = createAtom({ key: 'x', defaultValue: 0 });
export const positionYAtom = createAtom({ key: 'y', defaultValue: 0 });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 3. 生命周期管理
class MyComponent {
clearFns: (() => void)[] = [];
init() {
// 收集清理函数
this.clearFns.push(
observeSync(
() => pendantAtom.getValue().isVisible,
(prev, cur) => { /* ... */ }
)
);
this.clearFns.push(
observeAsync(
() => pendantAtom.getValue().position,
(prev, cur) => { /* ... */ }
)
);
}
destroy() {
// 统一清理
this.clearFns.forEach(fn => fn());
this.clearFns = [];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 4. 性能优化
// ✅ 使用 Partial 更新(推荐)
pendantAtom.setValue({
coinCount: 10 // 只更新 coinCount
});
// ✅ 批量更新
pendantAtom.setValue({
isReady: true,
isVisible: true,
coinCount: 10
});
// ❌ 避免频繁更新
for (let i = 0; i < 100; i++) {
pendantAtom.setValue({ coinCount: i }); // 触发 100 次更新
}
// ✅ 合并更新
let count = 0;
for (let i = 0; i < 100; i++) {
count++;
}
pendantAtom.setValue({ coinCount: count }); // 只触发 1 次更新
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 5. 避免循环依赖
// ❌ 循环依赖
export const atomA = createAtom({ key: 'a', defaultValue: 0 });
export const atomB = createAtom({ key: 'b', defaultValue: 0 });
observeSync(
() => atomA.getValue(),
(prev, cur) => {
atomB.setValue(cur); // A 变化导致 B 变化
}
);
observeSync(
() => atomB.getValue(),
(prev, cur) => {
atomA.setValue(cur); // B 变化导致 A 变化 → 循环!
}
);
// ✅ 使用单向数据流
observeSync(
() => atomA.getValue(),
(prev, cur) => {
// 只有 A 影响 B,B 不影响 A
atomB.setValue(cur * 2);
}
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 6. TypeScript 类型安全
// ✅ 定义明确的类型
interface PendantState {
isReady: boolean;
coinCount: number;
position: { x: number; y: number };
}
export const pendantAtom = createAtom<PendantState>({
key: 'pendant',
defaultValue: {
isReady: false,
coinCount: 0,
position: { x: 0, y: 0 }
}
});
// 类型检查
pendantAtom.setValue({
coinCount: '10' // ❌ 类型错误:应该是 number
});
pendantAtom.setValue({
coinCount: 10 // ✅ 正确
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 7. 调试技巧
// 添加调试名称
const unsubscribe = observeSync(
() => pendantAtom.getValue().coinCount,
(prev, cur) => {
console.log(`[God Pendant] 金币变化: ${prev} -> ${cur}`);
},
'god-coin-observer' // 调试名称
);
// 使用自定义比较函数
observeSync(
() => pendantAtom.getValue(),
(prev, cur) => {
console.log('状态变化', cur);
},
'pendant-full-state',
(a, b) => {
// 自定义比较逻辑
return a.coinCount === b.coinCount && a.isReady === b.isReady;
}
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 常见问题
# Q1: Atom 和 Redux 有什么区别?
Atom:
- 细粒度状态管理,每个 atom 是独立的状态片段
- 按需订阅,只更新依赖的组件
- 轻量级,几乎无样板代码
Redux:
- 单一状态树,所有状态在一个 store
- 通过 reducer 和 action 管理状态
- 适合大型项目,有完善的调试工具
# Q2: 什么时候应该拆分 Atom?
拆分原则:
- ✅ 状态相互独立,没有强关联
- ✅ 更新频率差异大
- ✅ 被不同组件单独使用
合并原则:
- ✅ 状态强相关,通常一起使用
- ✅ 业务逻辑内聚
- ✅ 避免过度拆分
# Q3: 如何处理异步数据?
// 方式 1: 在 atom 中存储异步状态
export const dataAtom = createAtom({
key: 'data',
defaultValue: {
loading: false,
data: null,
error: null
}
});
async function fetchData() {
dataAtom.setValue({ loading: true, error: null });
try {
const result = await api.getData();
dataAtom.setValue({ loading: false, data: result });
} catch (error) {
dataAtom.setValue({ loading: false, error });
}
}
// 方式 2: 使用 selector 处理异步(高级)
export const asyncDataSelector = createSelector(async () => {
const result = await api.getData();
return result;
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Q4: 如何避免内存泄漏?
// ✅ 正确的生命周期管理
class MyComponent {
clearFns: (() => void)[] = [];
componentDidMount() {
this.clearFns.push(
observeSync(/* ... */)
);
}
componentWillUnmount() {
// 必须清理订阅
this.clearFns.forEach(fn => fn());
this.clearFns = [];
// 如果 atom 不再使用,也应该销毁
myAtom.destroy();
}
}
// ✅ 使用 AtomClass 自动管理
class MyAtom extends AtomClass {
constructor() {
super('my', {});
// 订阅会自动管理
this.observeSync(/* ... */);
}
cleanup() {
this.destroy(); // 自动清理所有订阅
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 性能优化清单
- [ ] 使用 Partial 更新避免不必要的对象创建
- [ ] 批量更新多个属性,而不是多次单独更新
- [ ] 使用
observeAsync处理非关键路径更新 - [ ] 合理拆分 atom 粒度,避免大对象频繁更新
- [ ] 使用
shallowEqual或自定义比较函数避免误触发 - [ ] 及时销毁不再使用的订阅
- [ ] 避免在 observe 回调中进行昂贵的计算
# 参考资料
# 官方文档
- Recoil 官方文档 (opens new window)
- Jotai 官方文档 (opens new window)
- MobX 官方文档 (opens new window)
- Solid.js Reactivity (opens new window)
# 学术论文
- Reactive Programming (opens new window)
- Observer Pattern (opens new window)
- Functional Reactive Programming (opens new window)
# 推荐阅读
- 《响应式编程》 - Erik Meijer
- 《JavaScript 设计模式》 - Addy Osmani
- React State Management in 2024 (opens new window)
# 源码学习
# 附录
# A. 完整 API 列表
| API | 类型 | 说明 |
|---|---|---|
createAtom | Function | 创建状态原子 |
createSelector | Function | 创建派生状态 |
observeSync | Function | 同步监听 |
observeAsync | Function | 异步监听 |
AtomClass | Class | 封装类 |
rootAtom | Object | 全局状态管理器 |
shallowEqual | Function | 浅比较工具 |
# B. 设计模式
- 观察者模式:订阅-通知机制
- 单例模式:rootAtom 全局唯一
- 工厂模式:createAtom 创建 atom 实例
- 代理模式:getValue/setValue 代理访问
- 策略模式:自定义 isEqual 比较策略
# C. 版本历史
- v1.0.0 - 初始实现,支持基础 atom 功能
- v1.1.0 - 添加 selector 支持
- v1.2.0 - 优化性能,添加浅比较
- v1.3.0 - 添加 AtomClass 封装
- v2.0.0 - 支持依赖追踪和生命周期管理
最后更新:2025-10-28
维护者:Frontend Team
反馈:如有问题或建议,请提交 Issue
上次更新: 2025/10/31, 17:48:12