For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt, and this page is available as Markdown at /next/zh/react/state-management/zustand.md.
  • 简体中文
  • Zustand

    使用 zustand

    Zustand 是一个轻量、敏捷且可扩展的状态管理解决方案,基于 React Hooks 提供简洁易用的 API,既灵活又具备一定的规范性。

    安装依赖

    npm
    yarn
    pnpm
    bun
    deno
    npm install zustand

    示例

    import { useEffect } from '@lynx-js/react';
    import { create } from 'zustand';
    
    type State = {
      count: number;
    };
    
    type Action = {
      increment: () => void;
    };
    
    const useStore = create<State & Action>((set) => ({
      count: 0,
      increment: () => set((state) => ({ count: state.count + 1 })),
    }));
    
    export function App() {
      const { count, increment } = useStore();
    
      useEffect(() => {
        console.log('count changed:', count);
      }, [count]);
    
      return (
        <view>
          <text>{count}</text>
          <text bindtap={increment}>Tap</text>
        </view>
      );
    }

    更多细节请参考 zustand - guides

    除非另有说明,本项目采用知识共享署名 4.0 国际许可协议进行许可,代码示例采用 Apache License 2.0 许可协议进行许可。