@pixel-starry/hook-store
v1.0.0
Published
A light data management tool for react framework.
Readme
HookStore
HookStore 是一个轻量级的 React 状态管理 hooks 库,支持精细化更新。
store 定义
现在我们来编写一个计数器 store
import { BaseStore } from '@pixel-starry/hook-store';
class CountStore extends BaseStore {
count = 0;
count2 = 0;
add(num: number) {
this.setState({ count: num });
}
reset() {
this.setState({ count: 0 });
}
times(num: number) {
this.setState({ count: this.count * num });
}
}
使用 store
import { StoreProvider, useStore } from '@pixel-starry/hook-store';
const Child = () => {
const store = useStore(CountStore);
return (
<div>
<div>{store.count}</div>
<button onClick={() => store.add(1)}>加1</button>
<button onClick={() => store.times(2)}>乘2</button>
<button onClick={() => store.reset()}>复位</button>
</div>
);
};
const Root = () => {
return (
<StoreProvider store={CountStore}>
<Child />
</StoreProvider>
);
};
API
- BaseStore
store的基类,提供了 setState 来更新数据
- StoreProvider
Context Provider 组件,需要把当前的 store 传递给 Provider 组件
- withStore
StoreProvider 另一种用法, 用法 withStore(Child, CountStore);
const Root = withStore(Child, CountStore);- useStore
获取 store 实例,第一个参数是 BaseStore,第二个参数是更新依赖项。
如:
// 调用 setState 组件就会更新
const store = useStore(CountStore);
// 调用 setState 组件不会更新
const store = useStore(CountStore, []);
// 调用 setState 后, count值变化组件会更新,否则不会更新
const store = useStore(CountStore, ['count']);
