React 和 Zustand 狀態管理初學者指南
介紹
狀態管理對於任何 React 應用程式都至關重要,但像 Redux 這樣的傳統函式庫有時會讓人覺得大材小用。輸入 Zustand,這是一個最小且強大的 React 狀態管理解決方案。在這篇文章中,我們將深入探討為什麼 Zustand 成為開發人員的最愛,以及如何在 React 專案中開始使用它。
祖斯坦是什麼?
Zustand 是 React 的狀態管理函式庫,設計簡單直覺。它是輕量級的,不需要大量樣板,這使得它比 Redux 甚至 React Context API 更容易使用。讓我們看看如何在 React 應用程式中使用 Zustand。
在 React 中設定 Zustand
-
安裝 Zustand
npm install zustand
登入後複製 -
建立商店
以下是如何在 Zustand 中建立商店的簡單範例:
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
現在,讓我們在 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;
登入後複製
進階 Zustand 功能:get、getState
- Zustand 也提供了另外兩個有用的函數:get 和 getState。這些用於檢索狀態並獲取任意時間點的狀態
getState(): 此函數為您提供商店的當前狀態,而無需觸發重新渲染。
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(): 此函數可讓您直接從儲存本身存取狀態。如果您需要在設定之前或之後檢查或修改狀態,它非常有用。
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 中的切片
- 隨著應用程式的成長,最好將您的狀態組織成更小、更易於管理的部分。這就是切片發揮作用的地方。切片是一個模組化的狀態區塊,有自己的一組操作。每個切片都可以在自己的文件中定義,使您的程式碼更乾淨且更易於維護。
// 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), }));
如何使用內部組件
import { useBoundStore } from './useBoundStore' const App = () => { const { count, increase, decrease, user, setName } = useBoundStore(); }
Zustand 持續狀態
- Zustand 的持久中間件會在狀態發生變更時自動將其儲存到 localStorage,並在頁面重新載入時將其載入回來,確保狀態保持不變,而無需額外的工作。
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 取得數據
- 要從 Zustand 中的 API 取得數據,請在商店中建立操作來處理 API 呼叫並使用取得的資料、載入和錯誤狀態更新狀態。
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 狀態管理初學者指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python和JavaScript開發者的薪資沒有絕對的高低,具體取決於技能和行業需求。 1.Python在數據科學和機器學習領域可能薪資更高。 2.JavaScript在前端和全棧開發中需求大,薪資也可觀。 3.影響因素包括經驗、地理位置、公司規模和特定技能。

實現視差滾動和元素動畫效果的探討本文將探討如何實現類似資生堂官網(https://www.shiseido.co.jp/sb/wonderland/)中�...

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

學習JavaScript不難,但有挑戰。 1)理解基礎概念如變量、數據類型、函數等。 2)掌握異步編程,通過事件循環實現。 3)使用DOM操作和Promise處理異步請求。 4)避免常見錯誤,使用調試技巧。 5)優化性能,遵循最佳實踐。

如何在JavaScript中將具有相同ID的數組元素合併到一個對像中?在處理數據時,我們常常會遇到需要將具有相同ID�...

zustand異步操作中的數據更新問題在使用zustand狀態管理庫時,經常會遇到異步操作導致數據更新不及時的問題。 �...
