zustand-全局状态管理快速上手

117 阅读1分钟

官网地址:Zustand

  1. 安装依赖
pnpm i zustand
  1. 定义zustand状态hooks
// src/stores/useCount.ts

import { create } from 'zustand';

// 定义类型
type CountType = {
  count: number;
  increment: () => void;
  incrementBy: (amount: number) => void;
  decrement: () => void;
  reset: () => void;
};

// 定义hooks
export default create<CountType>(set => ({
  count: 0, // 状态初始值
  increment: () => set(state => ({ count: state.count + 1 })), // 加1
  decrement: () => set(state => ({ count: state.count - 1 })), // 减1
  incrementBy: (amount: number) => set(state => ({ count: state.count + amount })), // 加指定
  reset: () => set({ count: 0 }), // 重置0
}));
  1. 不同组件使用状态或修改状态
// src/App.tsx

import Son from './pages/Son';
import useCount from './stores/useCount';

export default function App() {
  const { count, increment } = useCount();

  return (
    <>
      <div>{count}</div>
      <button onClick={() => increment()}>加1</button>

      <Son />
    </>
  );
}
// src/pages/Son.tsx

import { useState } from 'react';
import useCount from '../stores/useCount';

export default function Son() {
  const countStore = useCount();
  const [num, setNum] = useState(1);
  return (
    <div style={{ width: 200, height: 200, border: '1px solid black', marginTop: 20 }}>
      <h3>子组件</h3>
      <div>{countStore.count}</div>
      <input type="number" defaultValue={num} onChange={e => setNum(Number(e.target.value))} />
      <button onClick={() => countStore.incrementBy(num)}>加{num}</button>
      <button onClick={() => countStore.reset()}>重置0</button>
    </div>
  );
}
  1. 效果