Next.js Zustand 的详细使用说明

25 min read

Next.js 是一个用于构建 React 应用程序的框架,而 Zustand 是一个用于状态管理的库。在 Next.js 中,可以使用 Zustand 来管理应用程序的全局状态。下面是一个详细的使用示例:

  1. 创建一个新的 Next.js 项目:

    npx create-next-app my-app
    cd my-app
    
  2. 安装 Zustand:

    npm install zustand
    
  3. pages 文件夹下创建一个 index.js 文件,并在其中定义一个状态管理器:

    import { useStore } from '../store';
    
    export default function Home() {
      const counter = useStore(state => state.counter);
      const increment = useStore(state => state.increment);
    
      return (
        <div>
          <h1>Counter: {counter}</h1>
          <button onClick={increment}>Increment</button>
        </div>
      );
    }
    
  4. store.js 文件中定义状态管理器:

    import create from 'zustand';
    
    export const useStore = create(set => ({
      counter: 0,
      increment: () => set(state => ({ counter: state.counter + 1 })),
    }));
    

    此处使用了 create 函数来创建一个状态管理器,传入一个 set 函数来更新状态。useStore 函数接收一个回调函数,用于选择需要访问的状态和动作。

  5. 运行应用程序:

    npm run dev
    

    现在,应用程序将会在 http://localhost:3000 上运行,你可以在浏览器中访问该地址来查看应用程序。每次点击按钮时,计数器的值将会增加。

这就是使用 Next.js 和 Zustand 创建一个简单的全局状态管理的过程。你可以根据自己的需要扩展和修改状态管理器来满足应用程序的需求。