TinyBase多Store类型定义的最佳实践
2025-06-13 12:39:08作者:邵娇湘
前言
TinyBase是一个轻量级的客户端状态管理库,其强大的类型系统为开发者提供了良好的类型安全保证。但在实际开发中,当我们需要管理多个具有不同Schema的Store时,类型定义可能会变得复杂。本文将详细介绍在TinyBase中如何优雅地处理多Store的类型定义问题。
基础概念
在TinyBase中,每个Store可以定义自己的TablesSchema和ValuesSchema。Schema定义了Store中数据的结构和类型,为后续的类型检查提供基础。
单Store类型定义
对于单个Store,类型定义相对简单:
import * as UiReact from 'tinybase/ui-react/with-schemas';
import {type NoValuesSchema, createStore} from 'tinybase/with-schemas';
const TABLES_SCHEMA = {
table1: {name: {type: 'string', default: ''}},
} as const;
type Schemas = [typeof TABLES_SCHEMA, NoValuesSchema];
const {Provider, useCreateStore} = UiReact as UiReact.WithSchemas<Schemas>;
多Store类型定义挑战
当应用需要多个Store时,每个Store可能有不同的Schema,这时类型定义会变得复杂。主要挑战在于:
- 如何为每个Store定义独立的Schema
- 如何在一个Provider中管理多个Store
- 如何在使用时正确获取类型提示
解决方案
方案一:独立组件模式
推荐的做法是为每个Store创建独立的React组件,这些组件负责初始化Store并将其注入到Provider中:
// JournalStore.tsx
import * as UiReact from 'tinybase/ui-react/with-schemas';
const TABLES_SCHEMA = {
journal: {date: {type: 'number'}, content: {type: 'string'}}
} as const;
type Schemas = [typeof TABLES_SCHEMA, NoValuesSchema];
const {useCreateStore} = UiReact as UiReact.WithSchemas<Schemas>;
export const journalStore = createStore().setTablesSchema(TABLES_SCHEMA);
export function JournalStoreProvider() {
useCreateStore(() => journalStore);
return null;
}
然后在根组件中组合使用:
function App() {
return (
<>
<JournalStoreProvider />
<SettingsStoreProvider />
{/* 其他组件 */}
</>
);
}
这种方式的优点是:
- 每个Store的类型定义独立清晰
- 易于维护和扩展
- 可以单独导出Store实例供其他代码使用
方案二:单文件多Store模式
如果希望在单个文件中管理多个Store,可以采用类型断言的方式:
import * as UiReact from 'tinybase/ui-react/with-schemas';
// 定义第一个Store的Schema
const SCHEMA_1 = {
table1: {field1: {type: 'string'}}
} as const;
type Schemas1 = [typeof SCHEMA_1, NoValuesSchema];
const {useCreateStore: useCreateStore1} = UiReact as UiReact.WithSchemas<Schemas1>;
// 定义第二个Store的Schema
const SCHEMA_2 = {
table2: {field2: {type: 'number'}}
} as const;
type Schemas2 = [typeof SCHEMA_2, NoValuesSchema];
const {useCreateStore: useCreateStore2} = UiReact as UiReact.WithSchemas<Schemas2>;
// 使用any类型定义Provider
const {Provider} = UiReact as UiReact.WithSchemas<any>;
function MultiStoreProvider({children}: {children: ReactNode}) {
const store1 = useCreateStore1(() => createStore().setTablesSchema(SCHEMA_1));
const store2 = useCreateStore2(() => createStore().setTablesSchema(SCHEMA_2));
return <Provider storesById={{store1, store2}}>{children}</Provider>;
}
类型安全使用Store
定义好Store后,使用时需要确保类型安全:
// 在使用处定义类型化的hooks
const {useCell: useJournalCell} =
UiReact as UiReact.WithSchemas<[typeof JournalSchema, NoValuesSchema]>;
function MyComponent() {
const value = useJournalCell('journalTable', 'row1', 'field1', 'journalStore');
// 现在value有正确的类型提示
}
处理Values类型
对于Values的定义和使用,同样需要类型安全:
const VALUES_SCHEMA = {
preference1: {type: 'string'},
preference2: {type: 'number'}
} as const;
type Schemas = [NoTablesSchema, typeof VALUES_SCHEMA];
const {useValue} = UiReact as UiReact.WithSchemas<Schemas>;
type ValueIds = keyof typeof VALUES_SCHEMA;
function usePreferenceValue(valueId: ValueIds) {
return useValue(valueId, 'preferencesStore');
}
处理索引和关系类型
虽然TinyBase没有直接提供索引和关系的类型定义,但我们可以手动定义:
type IndexIds = 'InstitutionsByDate' | 'OtherIndex';
type RelationshipIds = 'AssetsInstitution' | 'OtherRelationship';
function useCustomSlices(indexId: IndexIds) {
return useSliceIds(indexId, customIndexes);
}
最佳实践总结
- 优先考虑独立组件模式,每个Store有独立的定义文件
- 为每个Store定义清晰的Schema和类型别名
- 在使用处通过类型断言获取类型安全的hooks
- 对于复杂场景,可以适当使用any类型简化Provider定义
- 手动定义索引和关系的类型以确保类型安全
结语
TinyBase的类型系统虽然强大,但在多Store场景下需要开发者投入一些精力来确保类型安全。通过本文介绍的模式,开发者可以构建出既类型安全又易于维护的状态管理架构。随着对TinyBase理解的深入,开发者可以进一步探索更复杂的类型模式,以满足特定应用场景的需求。
登录后查看全文
热门项目推荐
相关项目推荐
PaddleOCR-VLPaddleOCR-VL 是一款顶尖且资源高效的文档解析专用模型。其核心组件为 PaddleOCR-VL-0.9B,这是一款精简却功能强大的视觉语言模型(VLM)。该模型融合了 NaViT 风格的动态分辨率视觉编码器与 ERNIE-4.5-0.3B 语言模型,可实现精准的元素识别。Python00- DDeepSeek-OCR暂无简介Python00
openPangu-Ultra-MoE-718B-V1.1昇腾原生的开源盘古 Ultra-MoE-718B-V1.1 语言模型Python00
HunyuanWorld-Mirror混元3D世界重建模型,支持多模态先验注入和多任务统一输出Python00
AI内容魔方AI内容专区,汇集全球AI开源项目,集结模块、可组合的内容,致力于分享、交流。03
Spark-Scilit-X1-13BFLYTEK Spark Scilit-X1-13B is based on the latest generation of iFLYTEK Foundation Model, and has been trained on multiple core tasks derived from scientific literature. As a large language model tailored for academic research scenarios, it has shown excellent performance in Paper Assisted Reading, Academic Translation, English Polishing, and Review Generation, aiming to provide efficient and accurate intelligent assistance for researchers, faculty members, and students.Python00
GOT-OCR-2.0-hf阶跃星辰StepFun推出的GOT-OCR-2.0-hf是一款强大的多语言OCR开源模型,支持从普通文档到复杂场景的文字识别。它能精准处理表格、图表、数学公式、几何图形甚至乐谱等特殊内容,输出结果可通过第三方工具渲染成多种格式。模型支持1024×1024高分辨率输入,具备多页批量处理、动态分块识别和交互式区域选择等创新功能,用户可通过坐标或颜色指定识别区域。基于Apache 2.0协议开源,提供Hugging Face演示和完整代码,适用于学术研究到工业应用的广泛场景,为OCR领域带来突破性解决方案。00- HHowToCook程序员在家做饭方法指南。Programmer's guide about how to cook at home (Chinese only).Dockerfile013
Spark-Chemistry-X1-13B科大讯飞星火化学-X1-13B (iFLYTEK Spark Chemistry-X1-13B) 是一款专为化学领域优化的大语言模型。它由星火-X1 (Spark-X1) 基础模型微调而来,在化学知识问答、分子性质预测、化学名称转换和科学推理方面展现出强大的能力,同时保持了强大的通用语言理解与生成能力。Python00- PpathwayPathway is an open framework for high-throughput and low-latency real-time data processing.Python00
项目优选
收起
OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
239
2.36 K
deepin linux kernel
C
24
6
React Native鸿蒙化仓库
JavaScript
216
291
暂无简介
Dart
539
118
仓颉编译器源码及 cjdb 调试工具。
C++
115
86
仓颉编程语言运行时与标准库。
Cangjie
122
97
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
998
589
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
589
115
Ascend Extension for PyTorch
Python
77
110
仓颉编程语言提供了 stdx 模块,该模块提供了网络、安全等领域的通用能力。
Cangjie
80
55