Zustand

  • 融合Redux和React

    ┌─────────────────────────────┐
    │ create() 返回的对象 │
    │ (既是 Hook,又是 Store) │
    └──────────────┬──────────────┘
    ┌─────────────┐   ┌─────────────┐
    │ React Hook │ │ Store 对象 │
    │ useStore(...) │ │ useStore.getState() │
    │ 组件内调用 │ │ useStore.setState() │
    │ 订阅状态变化 │ │ useStore.subscribe()│
    └───────────────┘ └────────────┘

  • Redux的写法
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import { createStore } from 'redux';
    import { Provider, useSelector, useDispatch } from 'react-redux';
    
    const handlers = {
      INCREMENT: (state) => ({ count: state.count + 1 }),
      DECREMENT: (state) => ({ count: state.count - 1 }),
    };
    
    function counterReducer(state = { count: 0 }, action) {
      const handler = handlers[action.type];
      return handler ? handler(state) : state;
    }
    
    const store = createStore(counterReducer);
    
    function Counter() {
      const count = useSelector((state) => state.count);
      const dispatch = useDispatch();
    
      return (
        <div>
          <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
          <span>{count}</span>
          <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
        </div>
      );
    }
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <Provider store={store}>
        <Counter />
      </Provider>
    );
  • hook的写法
    import React, { useState } from 'react';
    
    function useCounter() {
      const [count, setCount] = useState(0);
    
      // 直接定义两个方法
      const increment = () => setCount((c) => c + 1);
      const decrement = () => setCount((c) => c - 1);
    
      return { count, increment, decrement };
    }
    
    function Counter() {
      const { count, increment, decrement } = useCounter();
    
      return (
        <div>
          <button onClick={decrement}>-</button>
          <span>{count}</span>
          <button onClick={increment}>+</button>
        </div>
      );
    }
    
    export default Counter;
  • zustand的写法
    import create from 'zustand';
    
    // 创建 store
    const useCounterStore = create((set) => ({
      count: 0,
      increment: () => set((state) => ({ count: state.count + 1 })),
      decrement: () => set((state) => ({ count: state.count - 1 })),
    }));
    
    // React 组件
    function Counter() {
      const { count, increment, decrement } = useCounterStore();
      return (
        <div>
          <button onClick={decrement}>-</button>
          <span>{count}</span>
          <button onClick={increment}>+</button>
        </div>
      );
    }
    
    export default Counter;
    // 组件内用 Hook(自动订阅,触发组件更新)
    const count = useCounterStore(state => state.count);
    
    // 组件外(比如普通函数/工具函数)用 getState()
    const count = useCounterStore.getState().count;

     

    import React from 'react';
    import create from 'zustand';
    
    // 创建 store
    const useStore = create((set) => ({
      count: 0,
      increment: () => set(state => ({ count: state.count + 1 })),
      reset: () => set({ count: 0 }),
    }));
    
    // React 组件内使用
    function Counter() {
      const count = useStore(state => state.count);
      const increment = useStore(state => state.increment);
      const reset = useStore(state => state.reset);
    
      return (
        <div>
          <div>Count: {count}</div>
          <button onClick={increment}>+</button>
          <button onClick={reset}>Reset</button>
        </div>
      );
    }
    
    // 组件外普通函数中使用
    function outsideIncrement() {
      // 读取当前状态
      const currentCount = useStore.getState().count;
      console.log('Outside current count:', currentCount);
    
      // 直接修改状态
      useStore.setState(state => ({ count: state.count + 1 }));
    }
    
    export default function App() {
      return (
        <>
          <Counter />
          <button onClick={outsideIncrement}>Outside Increment</button>
        </>
      );
    }

     

posted @ 2025-07-31 11:12  瑞瑞大人  阅读(10)  评论(0)    收藏  举报