狀態管理對於任何 React 應用程式都至關重要,但像 Redux 這樣的傳統函式庫有時會讓人覺得大材小用。輸入 Zustand,這是一個最小且強大的 React 狀態管理解決方案。在這篇文章中,我們將深入探討為什麼 Zustand 成為開發人員的最愛,以及如何在 React 專案中開始使用它。
Zustand 是 React 的狀態管理函式庫,設計簡單直覺。它是輕量級的,不需要大量樣板,這使得它比 Redux 甚至 React Context API 更容易使用。讓我們看看如何在 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;
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 }, }));
// 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 持續狀態
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 } ) );
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中文網其他相關文章!