搜索
首页web前端js教程立即以最简单的方式学习 Zustand!

React 中的状态管理从未如此简单和轻量级! Zustand,一个小而强大的状态管理库,它将让您作为开发人员的生活变得更加轻松。无论您厌倦了 Redux 的样板文件还是 Context API 的限制,Zustand 都可以拯救您。

在这篇文章中,我将介绍 Zustand 并分享我构建的入门项目,可在 GitHub 上获取。按照说明,只需几个步骤即可在 Next.js 项目中开始使用 Zustand! ?

Learn Zustand Right Now in the Simplest Way!

祖斯坦是什么? ?

Zustand(德语“状态”)是 React 的简约状态管理库。它提供:

  • 一个超级简单的API。
  • 高性能,无需不必要的重新渲染。
  • 易于理解的语法。
  • 内置中间件支持(例如,用于持久状态)。

现在,让我们深入了解在您的 Next.js 项目中进行设置!


如何在您的 Next.js 项目中设置 Zustand

按照以下简单步骤将 Zustand 集成到您的 Next.js 应用程序中。

1.安装Zustand

运行以下命令来安装 Zustand:

npm i zustand

2. 创建存储文件夹

在 src 文件夹中,创建一个名为 store 的新文件夹。这将保存您所有的 Zustand 状态文件。

src/
  store/
    index.ts
    userStore.ts

3. 添加您的商店

userStore.ts

该商店将处理用户相关数据。

import { create } from "zustand";

interface User {
  id: string;
  name: string;
  email: string;
}

interface UserStore {
  user: User | null;
  setUser: (user: User | null) => void;
}

export const useUserStore = create<userstore>((set) => ({
  user: null,
  setUser: (user: User | null) => set({ user }),
}));
</userstore>

counterStore.ts(带有持久性)

该存储将处理计数器状态并将其保存在 localStorage 中。

"use client";

import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";

interface ICounterStore {
  counter: number;
  increment : ()=> void;
  decrement : ()=> void;
  reset : ()=> void;
  getLatestCountDivided2: ()=> number;
}
export const useCounterStore = create<icounterstore>()(
  persist(
    (set, get) => ({
      counter: 0,

      increment: () => set(state => ({ counter: state.counter + 1 })),
      decrement: () => set(state => ({ counter: state.counter - 1 })),
      reset: () => set({ counter: 0 }),
      getLatestCountDivided2: ()=> get().counter / 2,
    }),
    {
      name: "counter-store",
      storage: createJSONStorage(()=> localStorage),
    }
  )
);
</icounterstore>

index.ts

此文件将导出所有商店以便于导入。

import { useUserStore } from "./userStore";
import { useCounterStore } from "./counterStore";

export { useUserStore, useCounterStore };

4. 在组件中使用Zustand

以下是如何在 Next.js 组件中使用 Zustand 存储的示例。

Home.tsx

"use client";
import { useCounterStore, useUserStore } from "@/store";
import Link from "next/link";

export default function Home() {
  // Access Zustand stores
  const userStore = useUserStore();
  const counterStore = useCounterStore();

  const handleAddUser = () => {
    userStore.setUser({ id: "1", name: "Joodi", email: "mail@example.com" });
  };

  return (
    <div classname="">
      <div classname="flex gap-2 p-2">
        <link classname="p-2 border" href="/">Home
        <link classname="p-2 border" href="/about">About
        <link classname="p-2 border" href="/contact">Contact
      </div>
      <h1 id="Hello">Hello</h1>
      <h1 id="User-userStore-user-email">User: {userStore.user?.email}</h1>
      <button classname="bg-blue-500 rounded-md p-2 text-white" onclick="{handleAddUser}">
        Add User
      </button>

      <br>
      <h1 id="Counter-counterStore-counter">Counter: {counterStore.counter}</h1>
      <button classname="bg-blue-500 rounded-md text-white p-2" onclick="{counterStore.increment}">
        Increment
      </button>
      <button classname="bg-blue-500 rounded-md text-white p-2" onclick="{counterStore.decrement}">
        Decrement
      </button>
      <button classname="bg-blue-500 rounded-md text-white p-2" onclick="{counterStore.reset}">
        Reset
      </button>
    </div>
  );
}

启动项目存储库?

入门项目的完整代码可在 GitHub 上找到。它适合初学者,包含开始将 Zustand 与 Next.js 结合使用所需的一切。

克隆存储库并开始:

git clone https://github.com/MiladJoodi/Zustand_Starter_Project.git
cd Zustand_Starter_Project
npm install
npm run dev

开始使用 Zustand 轻松管理您的状态。让我知道您的想法,或分享您自己的用例! ?

以上是立即以最简单的方式学习 Zustand!的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JavaScript数据类型:浏览器和nodejs之间是否有区别?JavaScript数据类型:浏览器和nodejs之间是否有区别?May 14, 2025 am 12:15 AM

JavaScript核心数据类型在浏览器和Node.js中一致,但处理方式和额外类型有所不同。1)全局对象在浏览器中为window,在Node.js中为global。2)Node.js独有Buffer对象,用于处理二进制数据。3)性能和时间处理在两者间也有差异,需根据环境调整代码。

JavaScript评论:使用//和 / * * / * / * /JavaScript评论:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:开发人员的比较分析Python vs. JavaScript:开发人员的比较分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

Python vs. JavaScript:选择合适的工具Python vs. JavaScript:选择合适的工具May 08, 2025 am 12:10 AM

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript:了解每个的优势Python和JavaScript:了解每个的优势May 06, 2025 am 12:15 AM

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

Python vs. JavaScript:您应该学到哪种语言?Python vs. JavaScript:您应该学到哪种语言?May 03, 2025 am 12:10 AM

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具