1、Zustand的特点 Zustand提供了一个简单而强大的API,用于管理状态。它支持中间件、持久化、异步操作等高级特性,非常适合在React应用中使用。通过上述示例,你可以快速上手Zustand,并在项目中实现高效的状态管理。 1,安装Zustand npm i Zustand 2,创建Store 创建一个状态管理的Store。Store是一个自定义Hook,你可以将任何东西放入其中:原始值、对象、函数。 import { create } from 'zustand';
const useStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })), }));
3.在组件中使用Store 在React组件中,你可以通过自定义Hook来访问和修改状态。 import React from 'react' import useStore from './store' const Count = ( ) => { const { count, increment, decrement } = useStore( ); return (
Count: { count }
Increment Decrementexport default Counter 4.使用Immer中间件 Zustand支持Immer中间件,允许你以可变的方式更新状态,而底层依然保持不可变性。 import { create } from 'zustand' import { immer } from 'zustand/middleware/immer'
const useStore = create( immer((set) => ({ count: 0, increment:( ) => { set(() => { state.count += 1;//直接更新状态 }) } })) ) 5.持久化状态 你可以使用persist中间件来持久化状态,例如将状态存储在浏览器的localStorage中。 import { create } from 'zustand'; import { persist } from 'zustand/middleware';
const useStore = create( persist( (set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })), }), { name: 'counter-storage', // 存储的名称 } ) ); 6.异步操作 Zustand也支持异步操作。你可以在store中定义异步方法。 const useStore = create((set) => ({ count: 0, fetchData: async () => { const response = await fetch('api.example.com/data'); const data = await response.json(); set({ count: data.count }); }, })); 7.组件中使用异步操作 在组件中调用异步方法。 import React, { useEffect } from 'react'; import useStore from './store';
const DataFetcher = () => { const { count, fetchData } = useStore();
useEffect(() => { fetchData(); }, [fetchData]);
return (