jotai-state-tree: 一个基于 jotai 的状态管理库
基于 jotai 的2次封装库
项目主页: https://github.com/afeiship/jotai-state-tree
安装
yarn add @jswork/jotai-state-tree
使用
- main.tsx
- app.tsx
- modules/*.ts 目录
添加 Provider,并绑定 stores
import ReactDOM from 'react-dom/client';
import JotaiStateTree from '@jswork/jotai-state-tree';
import stores from './stores';
import App from './App.tsx';
import './index.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<JotaiStateTree stores={stores}>
<App />
</JotaiStateTree>
);
核心使用逻辑 App.tsx
import './App.css';
function App() {
const [action, setAction] = nx.$use('recorder.action');
return (
<>
<h1>jotai-state-tree: {action} </h1>
<button
onClick={() => {
nx.$set('recorder.action', 'record');
}}>
Record
</button>
<button
onClick={(e) => {
setAction('stop');
}}>
Stop
</button>
<button
onClick={(e) => {
// setAction('play');
nx.$set('recorder.action', 'play');
}}>
Play
</button>
</>
);
}
export default App;
moudles 目录
modules/index.ts 核心逻辑,webpack/vite 版同理。
const moduleFiles = import.meta.glob('./modules/**/*.ts', { eager: true });
const modules = Object.keys(moduleFiles).reduce((modules, modulePath) => {
const moduleName = modulePath.replace(/^\.\/modules\/(.*)\.\w+$/, '$1');
const value = moduleFiles[modulePath]!.default;
// modules[moduleName] = value;
nx.set(modules, moduleName.replace(/\//g,'.'), value);
return modules;
}, {} as Record<string, any>);
export default modules;
.
├── index.ts
└── modules
└── recorder.ts
types
添加文件到
src
目录下,文件名为:nx.env.d.ts
/// <reference types="@jswork/next" />
/// <reference types="@jswork/jotai-state-tree/@types" />