useStoreValue
订阅 store 变化并自动触发组件重新渲染
API 参考
语法
const state = useStoreValue(store, options?)
参数
store
: ZenBox store 实例options
(可选):pick
: 用于选择性订阅的属性名称数组deep
: 启用深度比较以处理嵌套对象(默认:false)
返回值
当前 store 状态,或使用 pick
选项时返回选定的属性。
示例
完整 Store 订阅
订阅所有 store 状态变化以实现完整响应式更新:
import { createStore, useStoreValue } from "zenbox";
const userStore = createStore({
name: "张三",
age: 30,
email: "zhangsan@example.com",
});
function UserProfile() {
// useStore 的任意属性发生变化,都会触发重新渲染
const user = useStoreValue(userStore);
return (
<div>
<h1>{user.name}</h1>
<p>年龄: {user.age}</p>
<p>邮箱: {user.email}</p>
</div>
);
}
选择性订阅
仅订阅所需属性以优化性能:
function UserName() {
// 仅在 'name' 变化时重新渲染
const { name } = useStoreValue(userStore, {
pick: ["name"],
});
return <h1>{name}</h1>;
}
function UserContact() {
// 仅在 'name' 或 'email' 变化时重新渲染
const { name, email } = useStoreValue(userStore, {
pick: ["name", "email"],
});
return (
<div>
<p>姓名: {name}</p>
<p>邮箱: {email}</p>
</div>
);
}
深度比较
对于需要深度比较的复杂嵌套对象:
const settingsStore = createStore({
theme: {
colors: { primary: "#blue", secondary: "#gray" },
typography: { fontSize: 16, fontFamily: "Arial" },
},
preferences: {
notifications: true,
autoSave: false,
},
});
function ThemeDisplay() {
const { theme } = useStoreValue(settingsStore, {
pick: ["theme"],
deep: true, // 启用深度比较,避免不必要的重新渲染
});
return (
<div style={{ color: theme.colors.primary }}>
主题: {theme.colors.primary}
</div>
);
}
最佳实践
✅ 大型 store 使用选择性订阅
// Good:仅订阅所需属性
const { name, status } = useStoreValue(largeStore, {
pick: ["name", "status"],
});
❌ 仅需要特定属性时避免完整订阅
// 低效:订阅所有状态变化
const store = useStoreValue(largeStore);
return <div>{store.name}</div>; // 仅使用 name,但订阅了所有状态
✅ 性能优先使用浅层监听
// 默认的浅层比较能够满足大多数情况
const user = useStoreValue(userStore);
❌ 非必要时不要使用深度监听
// 昂贵:仅在需要深度对象比较时使用
const data = useStoreValue(store, { deep: true });
Hook 比较
Hook | 用途 | 重新渲染 | 最适用于 |
---|---|---|---|
useStoreValue | 完整 store 订阅 | ✅ 是 | 所有 store 状态 |
usePick | 选择性属性订阅 | ✅ 是 | 特定属性 |
useComputed | 响应式更新的计算值 | ✅ 是 | 计算数据 |
useWatch | 监听状态变化并执行副作用 | ❌ 否 | 日志、API |
相关 Hook
usePick
- 按需订阅 store 指定状态变化useComputed
- 响应式更新的计算值useWatch
- 监听状态变化并执行副作用