Retalk,最简单的 Redux 解决方案,可以更简单一点吗?
Retalk 3.0,现在 —— 像写 React 一样来写 Redux。
GitHub
特性
- 极简 Redux - 与 React 组件相同的语法。
- 只有 3 个 API -
setStore()、withStore()、<Provider>。 - 异步 model - 对 model 进行代码分割的完整支持。
- 自动 loading - 自动生成异步 action 的 loading state。
安装
yarn add retalk
或
npm install retalk
使用
1. Models
通常我们会在 app 内设置多个路由,一个路由对应一个 model,所以将会有多个 model。
像写一个 React 组件一样来写 model,只是没有了生命周期而已。
class CounterModel {
state = {
count: 0,
};
increment() {
// this.state -> 获取自身 model 的 state
// this.setState() -> 更新自身 model 的 state
// this.someAction() -> 调用自身 model 的 action
// this.models.someModel.state -> 获取其它 model 的 state
// this.models.someModel.someAction() -> 调用其它 model 的 action
const { count } = this.state;
this.setState({ count: count + 1 });
}
async incrementAsync() {
// 自动生成的 `someAsyncAction.loading` state 可供使用
await new Promise((resolve) => setTimeout(resolve, 1000));
this.increment();
}
}
2. Store
使用 setStore() 来初始化所有 model 与其命名空间。
import { setStore } from 'retalk';
const store = setStore({
counter: CounterModel,
// 其它 model...
});
3. Views
使用 withStore() 来连接 model 与组件。
import React from 'react';
import { withStore } from 'retalk';
const Counter = ({ count, increment, incrementAsync }) => (
<div>
<p>{count}</p>
<button onClick={increment}>+</button>
<button onClick={incrementAsync}>+ Async{incrementAsync.loading && '...'}</button>
</div>
);
const CounterWrapper = withStore('counter')(Counter);
4. App
使用 <Provider> 来将 store 提供给 app。
import ReactDOM from 'react-dom';
import { Provider } from 'retalk';
const App = () => (
<Provider store={store}>
<CounterWrapper />
</Provider>
);
ReactDOM.render(<App />, document.getElementById('root'));
示例
API
1. setStore()
2. withStore()
3. <Provider>
FAQ
1. 异步引入 model?
2. 自定义 state 与 action?
3. 支持热更新?
从 v2 升级到 v3
如果你已经使用过 Retalk 2.0,可根据文档升级到 3.0,一切都非常简单。^_^
最后
最简单的 Redux 开发体验,欢迎尝试:
定不负所望~ ⚡️