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

首頁(yè) web前端 js教程 React 和 Zustand 狀態(tài)管理初學(xué)者指南

React 和 Zustand 狀態(tài)管理初學(xué)者指南

Dec 27, 2024 am 07:37 AM

A Beginner’s Guide to State Management in React with Zustand

介紹

狀態(tài)管理對(duì)於任何 React 應(yīng)用程式都至關(guān)重要,但像 Redux 這樣的傳統(tǒng)函式庫(kù)有時(shí)會(huì)讓人覺(jué)得大材小用。輸入 Zustand,這是一個(gè)最小且強(qiáng)大的 React 狀態(tài)管理解決方案。在這篇文章中,我們將深入探討為什麼 Zustand 成為開(kāi)發(fā)人員的最愛(ài),以及如何在 React 專案中開(kāi)始使用它。

祖斯坦是什麼?

Zustand 是 React 的狀態(tài)管理函式庫(kù),設(shè)計(jì)簡(jiǎn)單直覺(jué)。它是輕量級(jí)的,不需要大量樣板,這使得它比 Redux 甚至 React Context API 更容易使用。讓我們看看如何在 React 應(yīng)用程式中使用 Zustand。

在 React 中設(shè)定 Zustand

  • 安裝 Zustand

    npm install zustand
    
  • 建立商店
    以下是如何在 Zustand 中建立商店的簡(jiǎn)單範(fàn)例:

    import {create} from 'zustand';
    
    const useStore = create((set) => ({
      count: 0,
      increase: () => set((state) => ({ count: state.count + 1 })),
      decrease: () => set((state) => ({ count: state.count - 1 })),
    }));
    
  • 在組件中使用 Store
    現(xiàn)在,讓我們?cè)?React 元件中使用 store:

    import React from 'react';
    import { useStore } from './store';
    
    const Counter = () => {
      const { count, increase, decrease } = useStore();
    
      return (
        <div>
          <h1>{count}</h1>
          <button onClick={increase}>Increase</button>
          <button onClick={decrease}>Decrease</button>
        </div>
      );
    };
    
    export default Counter;
    

進(jìn)階 Zustand 功能:get、getState

  • Zustand 也提供了另外兩個(gè)有用的函數(shù):get 和 getState。這些用於檢索狀態(tài)並獲取任意時(shí)間點(diǎn)的狀態(tài)

getState(): 此函數(shù)為您提供商店的當(dāng)前狀態(tài),而無(wú)需觸發(fā)重新渲染。

import {create} from 'zustand';

const useStore = create((set) => ({
  count: 0,
  increase: () => set((state) => ({ count: state.count + 1 })),
  decrease: () => set((state) => ({ count: state.count - 1 })),
}));

// Accessing the current state using getState()
const count= useStore.getState().count;

// Reading the current state value
console.log(count); // This will log the current count

// Modifying the state using the actions
store.increase(); // This will increase the count
console.log(store.count); // This will log the updated count

get(): 此函數(shù)可讓您直接從儲(chǔ)存本身存取狀態(tài)。如果您需要在設(shè)定之前或之後檢查或修改狀態(tài),它非常有用。

import {create} from 'zustand';

const useStore = create((set, get) => ({
  count: 0,
  increase: (amount) => {
    const currentState = get(); // Access the current state using getState()
    console.log("Current count:", currentState.count); // Log the current count
    set((state) => ({ count: state.count + amount })); // Modify the state
  },
})); 

Zustand 中的切片

  • 隨著應(yīng)用程式的成長(zhǎng),最好將您的狀態(tài)組織成更小、更易於管理的部分。這就是切片發(fā)揮作用的地方。切片是一個(gè)模組化的狀態(tài)區(qū)塊,有自己的一組操作。每個(gè)切片都可以在自己的文件中定義,使您的程式碼更乾淨(jìng)且更易於維護(hù)。
// counterStore.js
export const createCounterSlice = (set) => ({
  count: 0,
  increase: () => set((state) => ({ count: state.count + 1 })),
  decrease: () => set((state) => ({ count: state.count - 1 })),
});

// userStore.js
export const createUserSlice = (set) => ({
  user: { name: 'John Doe' },
  setName: (name) => set({ user: { name } }),
});

// useBoundStore.js
import {create} from 'zustand';
import { createCounterSlice } from './counterStore';
import { createUserSlice } from './userStore';

export const useBoundStore = create((...a) => ({
  ...createCounterSlice(...a),
  ...createUserSlice(...a),
}));

如何使用內(nèi)部組件

import { useBoundStore } from './useBoundStore'
const App = () => {
  const { count, increase, decrease, user, setName } = useBoundStore();
}

Zustand 持續(xù)狀態(tài)

  • Zustand 的持久中間件會(huì)在狀態(tài)發(fā)生變更時(shí)自動(dòng)將其儲(chǔ)存到 localStorage,並在頁(yè)面重新載入時(shí)將其載入回來(lái),確保狀態(tài)保持不變,而無(wú)需額外的工作。
import {create} from 'zustand';
import { persist } from 'zustand/middleware';

const useStore = create(
  persist(
    (set) => ({
      count: 0,
      increase: () => set((state) => ({ count: state.count + 1 })),
      decrease: () => set((state) => ({ count: state.count - 1 })),
    }),
    {
      name: 'counter-storage', // The name of the key in localStorage
    }
  )
);

從 Zustand 中的 API 取得數(shù)據(jù)

  • 要從 Zustand 中的 API 取得數(shù)據(jù),請(qǐng)?jiān)谏痰曛薪⒉僮鱽?lái)處理 API 呼叫並使用取得的資料、載入和錯(cuò)誤狀態(tài)更新?tīng)顟B(tài)。
import {create} from 'zustand';

const useStore = create((set) => ({
  users: [], // Array to store fetched users
  loading: false, // State to track loading status
  error: null, // State to track any errors during API call

  // Action to fetch users from the API
  fetchUsers: async () => {
    set({ loading: true, error: null }); // Set loading state to true and reset error
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      const data = await response.json();
      set({ users: data, loading: false }); // Set users data and loading to false
    } catch (error) {
      set({ error: 'Failed to fetch users', loading: false }); // Set error if fetch fails
    }
  },
}));

export default useStore;

以上是React 和 Zustand 狀態(tài)管理初學(xué)者指南的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)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脫衣器

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)

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ù)類型 JavaScript:探索用於高效編碼的數(shù)據(jù)類型 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.替換重型依賴,選用輕量級(jí)庫(kù)如day.js、fetch

See all articles