作为一个被Redux boilerplate折磨多年的前端er,今天我要安利一个让我眼前一亮的库------easy-model。
先说说我的踩坑史
还记得当年学Redux的时候吗?
- 先装
redux和react-redux - 定义
action types - 写
actions - 写
reducers - 配置
store - 用
connect包装组件... - 最后还要写
selectors
一个简单的计数器,写了将近100行代码。
后来转MobX,装饰器倒是爽,但TypeScript类型推来推去总出问题,而且那个隐式的依赖追踪,看代码时完全不知道谁在监听谁。
再后来用Zustand,哇,真TM简洁!但用久了总感觉缺点什么------没有类模型的组织方式,状态一多就成了"函数大杂烩"。
直到遇到easy-model
tsx
// 一个计数器,只要这么几行
class CounterModel {
count = 0;
increment() {
this.count += 1;
}
decrement() {
this.count -= 1;
}
}
function Counter() {
const counter = useModel(CounterModel, []);
return (
<div>
<div>计数: {counter.count}</div>
<button onClick={() => counter.increment()}>+</button>
<button onClick={() => counter.decrement()}>-</button>
</div>
);
}
这才是人写的代码!
它到底好在哪?
1. 类模型,写起来就是爽
tsx
class UserModel {
userInfo: User | null = null;
loading = false;
async fetchUser(id: string) {
this.loading = true;
const res = await api.getUser(id);
this.userInfo = res;
this.loading = false;
}
}
字段就是状态,方法就是业务逻辑。没有actions,没有reducers,什么都没有!
2. 依赖注入,骚操作来了
tsx
// 先定义schema
const userSchema = object({
id: number(),
name: string(),
}).describe("用户");
// 注入一个服务
class UserService {
@inject(userSchema)
user?: User;
}
// 配置
config(
<Container>
<CInjection schema={userSchema} ctor={UserService} />
</Container>,
);
这不妥妥的Spring Boot既视感?
3. 深度监听,想监听什么监听什么
tsx
class OrderModel {
order: Order = { items: [], total: 0 };
user: User = { name: "" };
}
watch(order, (keys, prev, next) => {
// keys 是 ['items', 0, 'price'] 这样的数组
console.log(`${keys.join(".")} 变了`, prev, "->", next);
});
嵌套对象、跨实例引用、getter返回的实例...全都能监听!
4. 性能居然比MobX还快
官方有个benchmark,10万个元素的数组批量更新5轮:
- easy-model: ~3ms
- MobX: ~17ms
- Redux: ~52ms
- Zustand: ~0.6ms(最快,但它没有IoC能力)
在有IoC能力的状态管理方案里,easy-model基本没有对手。
对比一下
| 特性 | easy-model | Redux | MobX | Zustand |
|---|---|---|---|---|
| 类模型 | ✅ | ❌ | ✅ | ❌ |
| IoC/DI | ✅ | ❌ | ❌ | ❌ |
| 深度监听 | ✅ | ❌ | ✅ | ✅ |
| 性能 | 快 | 慢 | 中 | 最快 |
| 学习成本 | 低 | 高 | 中 | 低 |
适合谁用?
- 喜欢用类来组织业务代码的
- 需要依赖注入的(比如仓储模式)
- 对"监听嵌套字段变化"有强需求的
- 不想被Redux boilerplate逼疯的
怎么入门?
bash
pnpm add @e7w/easy-model
官方文档很详细,中英文都有。GitHub上也有完整的example和test。
一句话总结:这是近年来我用过最"对胃口"的状态管理方案。
Github地址:github.com/ZYF93/easy-... 如果觉得不错,点个star支持下呗 🙏