国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁(yè) web前端 js教程 立即以最簡(jiǎn)單的方式學(xué)習(xí) Zustand!

立即以最簡(jiǎn)單的方式學(xué)習(xí) Zustand!

Dec 15, 2024 pm 03:46 PM

React 中的狀態(tài)管理從未如此簡(jiǎn)單和輕量級(jí)! Zustand,一個(gè)小而強(qiáng)大的狀態(tài)管理庫(kù),它將讓您作為開(kāi)發(fā)人員的生活變得更加輕松。無(wú)論您厭倦了 Redux 的樣板文件還是 Context API 的限制,Zustand 都可以拯救您。

在這篇文章中,我將介紹 Zustand 并分享我構(gòu)建的入門(mén)項(xiàng)目,可在 GitHub 上獲取。按照說(shuō)明,只需幾個(gè)步驟即可在 Next.js 項(xiàng)目中開(kāi)始使用 Zustand! ?

Learn Zustand Right Now in the Simplest Way!

祖斯坦是什么? ?

Zustand(德語(yǔ)“狀態(tài)”)是 React 的簡(jiǎn)約狀態(tài)管理庫(kù)。它提供:

  • 一個(gè)超級(jí)簡(jiǎn)單的API。
  • 高性能,無(wú)需不必要的重新渲染。
  • 易于理解的語(yǔ)法。
  • 內(nèi)置中間件支持(例如,用于持久狀態(tài))。

現(xiàn)在,讓我們深入了解在您的 Next.js 項(xiàng)目中進(jìn)行設(shè)置!


如何在您的 Next.js 項(xiàng)目中設(shè)置 Zustand

按照以下簡(jiǎn)單步驟將 Zustand 集成到您的 Next.js 應(yīng)用程序中。

1.安裝Zustand

運(yùn)行以下命令來(lái)安裝 Zustand:

npm i zustand

2. 創(chuàng)建存儲(chǔ)文件夾

在 src 文件夾中,創(chuàng)建一個(gè)名為 store 的新文件夾。這將保存您所有的 Zustand 狀態(tài)文件。

src/
  store/
    index.ts
    userStore.ts

3. 添加您的商店

userStore.ts

該商店將處理用戶相關(guān)數(shù)據(jù)。

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 }),
}));

counterStore.ts(帶有持久性)

該存儲(chǔ)將處理計(jì)數(shù)器狀態(tài)并將其保存在 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),
    }
  )
);

index.ts

此文件將導(dǎo)出所有商店以便于導(dǎo)入。

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

export { useUserStore, useCounterStore };

4. 在組件中使用Zustand

以下是如何在 Next.js 組件中使用 Zustand 存儲(chǔ)的示例。

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>
        <Link className="p-2 border" href="/about">About</Link>
        <Link className="p-2 border" href="/contact">Contact</Link>
      </div>
      <h1>Hello</h1>
      <h1>User: {userStore.user?.email}</h1>
      <button
        className="bg-blue-500 rounded-md p-2 text-white"
        onClick={handleAddUser}
      >
        Add User
      </button>

      <br />
      <h1>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>
  );
}

啟動(dòng)項(xiàng)目存儲(chǔ)庫(kù)?

入門(mén)項(xiàng)目的完整代碼可在 GitHub 上找到。它適合初學(xué)者,包含開(kāi)始將 Zustand 與 Next.js 結(jié)合使用所需的一切。

克隆存儲(chǔ)庫(kù)并開(kāi)始:

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

開(kāi)始使用 Zustand 輕松管理您的狀態(tài)。讓我知道您的想法,或分享您自己的用例! ?

以上是立即以最簡(jiǎn)單的方式學(xué)習(xí) Zustand!的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請(qǐng)聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)代碼編輯軟件(SublimeText3)

熱門(mén)話題

Java vs. JavaScript:清除混亂 Java vs. JavaScript:清除混亂 Jun 20, 2025 am 12:27 AM

Java和JavaScript是不同的編程語(yǔ)言,各自適用于不同的應(yīng)用場(chǎng)景。Java用于大型企業(yè)和移動(dòng)應(yīng)用開(kāi)發(fā),而JavaScript主要用于網(wǎng)頁(yè)開(kāi)發(fā)。

JavaScript評(píng)論:簡(jiǎn)短說(shuō)明 JavaScript評(píng)論:簡(jiǎn)短說(shuō)明 Jun 19, 2025 am 12:40 AM

JavascriptconcommentsenceenceEncorenceEnterential gransimenting,reading and guidingCodeeXecution.1)單inecommentsareusedforquickexplanations.2)多l(xiāng)inecommentsexplaincomplexlogicorprovideDocumentation.3)

如何在JS中與日期和時(shí)間合作? 如何在JS中與日期和時(shí)間合作? Jul 01, 2025 am 01:27 AM

JavaScript中的日期和時(shí)間處理需注意以下幾點(diǎn):1.創(chuàng)建Date對(duì)象有多種方式,推薦使用ISO格式字符串以保證兼容性;2.獲取和設(shè)置時(shí)間信息可用get和set方法,注意月份從0開(kāi)始;3.手動(dòng)格式化日期需拼接字符串,也可使用第三方庫(kù);4.處理時(shí)區(qū)問(wèn)題建議使用支持時(shí)區(qū)的庫(kù),如Luxon。掌握這些要點(diǎn)能有效避免常見(jiàn)錯(cuò)誤。

為什么要將標(biāo)簽放在的底部? 為什么要將標(biāo)簽放在的底部? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript與Java:開(kāi)發(fā)人員的全面比較 JavaScript與Java:開(kāi)發(fā)人員的全面比較 Jun 20, 2025 am 12:21 AM

JavaScriptIspreferredforredforwebdevelverment,而Javaisbetterforlarge-ScalebackendsystystemsandSandAndRoidApps.1)JavascriptexcelcelsincreatingInteractiveWebexperienceswebexperienceswithitswithitsdynamicnnamicnnamicnnamicnnamicnemicnemicnemicnemicnemicnemicnemicnemicnddommanipulation.2)

什么是在DOM中冒泡和捕獲的事件? 什么是在DOM中冒泡和捕獲的事件? Jul 02, 2025 am 01:19 AM

事件捕獲和冒泡是DOM中事件傳播的兩個(gè)階段,捕獲是從頂層向下到目標(biāo)元素,冒泡是從目標(biāo)元素向上傳播到頂層。1.事件捕獲通過(guò)addEventListener的useCapture參數(shù)設(shè)為true實(shí)現(xiàn);2.事件冒泡是默認(rèn)行為,useCapture設(shè)為false或省略;3.可使用event.stopPropagation()阻止事件傳播;4.冒泡支持事件委托,提高動(dòng)態(tài)內(nèi)容處理效率;5.捕獲可用于提前攔截事件,如日志記錄或錯(cuò)誤處理。了解這兩個(gè)階段有助于精確控制JavaScript響應(yīng)用戶操作的時(shí)機(jī)和方式。

JavaScript:探索用于高效編碼的數(shù)據(jù)類(lèi)型 JavaScript:探索用于高效編碼的數(shù)據(jù)類(lèi)型 Jun 20, 2025 am 12:46 AM

javascripthassevenfundaMentalDatatypes:數(shù)字,弦,布爾值,未定義,null,object和symbol.1)numberSeadUble-eaduble-ecisionFormat,forwidevaluerangesbutbecautious.2)

如何減少JavaScript應(yīng)用程序的有效載荷大??? 如何減少JavaScript應(yīng)用程序的有效載荷大小? Jun 26, 2025 am 12:54 AM

如果JavaScript應(yīng)用加載慢、性能差,問(wèn)題往往出在payload太大,解決方法包括:1.使用代碼拆分(CodeSplitting),通過(guò)React.lazy()或構(gòu)建工具將大bundle拆分為多個(gè)小文件,按需加載以減少首次下載量;2.移除未使用的代碼(TreeShaking),利用ES6模塊機(jī)制清除“死代碼”,確保引入的庫(kù)支持該特性;3.壓縮和合并資源文件,啟用Gzip/Brotli和Terser壓縮JS,合理合并文件并優(yōu)化靜態(tài)資源;4.替換重型依賴(lài),選用輕量級(jí)庫(kù)如day.js、fetch

See all articles