快速开始
本页以 React 为主线,带你用最短路径跑通 IO:安装、创建状态、组件读取更新。 如果你要处理请求、重试、取消、分页,直接从 Query 专题 开始。
安装核心包与 React 适配(任选一种包管理工具):
npm install @iostore/store @iostore/reactpnpm add @iostore/store @iostore/reactyarn add @iostore/store @iostore/reactbun add @iostore/store @iostore/react2. 创建状态(store.ts)
Section titled “2. 创建状态(store.ts)”import { io } from '@iostore/store';
export const counterStore = io({ count: 0, user: { name: 'Ada' },});3. 在 React 组件中使用(Counter.tsx)
Section titled “3. 在 React 组件中使用(Counter.tsx)”import { useIO } from '@iostore/react';import { counterStore } from './store';
export function Counter() { const state = useIO(counterStore);
return ( <div> <p> {state.user.name}: {state.count} </p> <button onClick={() => counterStore.count.set((v) => v + 1)}>+1</button> <button onClick={() => counterStore.user.name.set('Grace')}>Rename</button> </div> );}你会得到两个关键体验:
- 可以直接更新深层路径:
counterStore.user.name.set('Grace') - 只用一次
useIO,组件上手更快
4. 可选:更细粒度订阅
Section titled “4. 可选:更细粒度订阅”当你只关心某个叶子字段时,直接订阅路径 Unit 能进一步减少渲染:
import { useIO } from '@iostore/react';import { counterStore } from './store';
export function CountOnly() { const count = useIO(counterStore.count); return <span>{count}</span>;}5. 可选:加入派生值
Section titled “5. 可选:加入派生值”import { derived } from '@iostore/store/derived';import { counterStore } from './store';
export const doubled = derived(counterStore, (s) => s.count * 2);- 不要在数组里重复放同一个对象实例;每个元素都创建新对象。
- 当组件订阅的是路径 Unit 时,避免用整数组/对象替换方式“重置”;优先更新路径本身。