Ractor
一个基于 action 设计的状态管理工具
安装
npm i ractor
复制代码
快速了解 Ractor
Ractor 仅仅包含三个基本概念,您只需要熟悉这三样东西就能彻底掌握 Ractor 的用法。
System
和其他库有所区别, Ractor 的事件系统和逻辑系统是分开的,需要单独创建。一般情况下,您只需要为你的 App 创建一个事件系统。
import { System } from "ractor";
export const system = new System("counter");
复制代码
Action
类似 Redux 的 action,不过 Ractor 需要用 class 创建它。
export class Increment {}
复制代码
Store
通俗的说,你可以把 Ractor 的 Store 理解为 Redux 的 Store。唯一的区别是,Redux 的 Store 内置了一套事件分发机制,Ractor 的事件分发由 System 处理。
Store 是个抽象类,你的业务 Store 需要继承它并实现 createReceive 方法。Store 里有个很方便的工具类可以帮您构建用来处理事件的 Receive 对象。
import { Increment } from "./Increment";
import { Decrement } from "./Decrement";
import { Store } from "ractor";
export class CounterStore extends Store<{ value: number }> {
public state = { value: 1 };
public createReceive() {
return this.receiveBuilder()
.match(Increment, async () => this.setState({ value: this.state.value + 1 }))
.match(Decrement, async () => this.setState({ value: this.state.value - 1 }))
.build();
}
}
复制代码
除了 class 创建 Store 之外,Ractor 还提供了比较简单的创建方式 createStore
import { ReceiveBuilder } from "ractor"
const CounterStore = createStore((state, replaceState) => {
return ReceiveBuilder
.create()
.match(Increment, () => replaceState(state + 1))
.match(Decrement, () => replaceState(state - 1))
.build()
})
复制代码
React
我们可以用 ractor-react 也可以用 ractor-hooks 搭配 React 使用。这里主要介绍 ractor-hooks
。
Provider
在这里注入 system
import { Provider } from "ractor-hooks"
import { System } from "ractor"
function App() {
return <Provider system={new System("app")}><Counter /></Provider>
}
复制代码
useStore
输入 Ractor Store 的子类作为参数,输出实例化之后的状态。
function Counter() {
const counter = useStore(CounterStore)
return jsx
}
复制代码
useSystem
输出 Provider
注入的 system。建议直接倒入 system,不太建议使用这种方式获取 system。
function Counter() {
const system = useSystem(CounterStore)
system.dispatch(new Increment)
return jsx
}
复制代码
Examples
FAQ
Ractor 如何读?
ruakter
Ractor 解决了什么问题?
Ractor 和 Redux 一样是基于 action 设计的一套状态管理系统。主要是帮助 App 管理各种各样的状态,包括全局的和临时的。
为什么称 Ractor 为下一代状态管理库?
Ractor 能管理程序的所有状态,并且有动态加载,依赖注入的能力。
如何写异步?
异步函数。
.match(AnyAction, async ({url}) => {
const user = await fetch(url)
this.setState({user})
})
复制代码
为什么 Ractor Store 不是纯的?
不太建议隔离副作用,这是权衡之后的决定。不过也可以只在 Store 里面写纯的逻辑,副作用可以交给 EffectStore 处理。这取决于你怎么架构。
为什么事件分发和逻辑处理要分开设计,有什么优势吗?
设计之处发现 Redux 只适合存储全局状态,本地状态需要通信需要其他库,比如 mobx 或者 context api。事件和逻辑分开之后就能随时注册和卸载"部分"逻辑。全局状态和临时状态都能存在 Ractor 里面,而且不需要的时候可以卸载它们。
其他
专栏:zhuanlan.zhihu.com/c_136750016
github: github.com/FE-Ractor/r…