快速开始

3 分钟快速上手 ZenBox

安装

npm install zenbox

基本用法

创建 Store

使用 createStore 创建带有初始状态的 store:

import { createStore } from "zenbox";

// 自动类型推导,无需手写 interface
const counterStore = createStore({ count: 0 });

读取状态

通过 store.value 访问当前状态:

const count = counterStore.value.count;

更新状态

使用 store.setState 更新状态(支持 Immer 的写法):

counterStore.setState((state) => {
  state.count++;
});

在组件中使用

使用 useStoreValue 订阅状态变化:

import { useStoreValue } from "zenbox";

function Counter() {
  const { count } = useStoreValue(counterStore);

  function increment() {
    counterStore.setState((state) => {
      state.count++;
    });
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>增加</button>
    </div>
  );
}

像 Vue 一样的写法

使用 Vue 风格的 hooks 进行响应式编程:

function DoubleCount() {
  const doubleCount = useComputed(() => counterStore.value.count * 2);

  return <p>doubleCount: {doubleCount}</p>;
}

function CountWatcher() {
  useWatch(
    () => counterStore.value.count,
    (current, prev) => {
      console.log("从", prev, "变为", current);
    }
  );

  useWatchEffect(() => {
    if (counterStore.value.count > 10) {
      console.log("count 超过 10");
    }
  });

  return <p>监听计数变化...</p>;
}

下一步: 查看使用指南了解更多用法和最佳实践。