状态管理对于任何 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中文网其他相关文章!