Zustandsverwaltung ist für jede React-Anwendung von entscheidender Bedeutung, aber traditionelle Bibliotheken wie Redux können manchmal übertrieben wirken. Geben Sie Zustand ein, eine minimale und leistungsstarke Zustandsverwaltungslösung für React. In diesem Beitrag gehen wir darauf ein, warum Zustand zu einem Favoriten für Entwickler wird und wie Sie damit in Ihren React-Projekten beginnen können.
Zustand ist eine Zustandsverwaltungsbibliothek für React, die einfach und intuitiv gestaltet ist. Es ist leichtgewichtig und erfordert nicht viel Boilerplate, was die Verwendung einfacher macht als Redux oder sogar die React Context API. Werfen wir einen Blick darauf, wie wir Zustand in unseren React-Anwendungen verwenden können.
Installationszustand
npm install zustand
Einen Shop erstellen
Hier ist ein einfaches Beispiel für die Erstellung eines Shops im 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 })), }));
Verwenden des Stores in einer Komponente
Jetzt verwenden wir den Store in einer React-Komponente:
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(): Diese Funktion gibt Ihnen den aktuellen Status des Stores, ohne ein erneutes Rendern auszulösen.
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(): Mit dieser Funktion können Sie direkt aus dem Store selbst auf den Status zugreifen. Dies ist nützlich, wenn Sie den Status vor oder nach dem Festlegen überprüfen oder ändern müssen.
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), }));
So verwenden Sie die Innenkomponente
import { useBoundStore } from './useBoundStore' const App = () => { const { count, increase, decrease, user, setName } = useBoundStore(); }
Anhaltender Zustand im 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;
Das obige ist der detaillierte Inhalt vonEin Leitfaden für Einsteiger zum Zustandsmanagement in React with Zustand. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!