Zustand介紹與使用 React狀態(tài)管理工具的解決方案
前言
在現(xiàn)代前端開發(fā)中,狀態(tài)管理一直是一個(gè)關(guān)鍵的挑戰(zhàn)。隨著應(yīng)用規(guī)模的擴(kuò)大,組件間的狀態(tài)共享變得愈加復(fù)雜。為了應(yīng)對這一需求,開發(fā)者們逐漸尋找更加輕量、靈活的解決方案。在眾多狀態(tài)管理庫中,Zustand 以其簡潔易用的特點(diǎn)脫穎而出。
Zustand 是一個(gè)基于 React 的狀態(tài)管理庫,旨在提供簡單而強(qiáng)大的狀態(tài)管理功能。與傳統(tǒng)的狀態(tài)管理工具相比,Zustand 采用了更為直觀的 API 設(shè)計(jì),降低了學(xué)習(xí)成本,讓開發(fā)者能夠快速上手。它的核心理念是“最小化”,意味著你可以只為應(yīng)用中需要的部分狀態(tài)創(chuàng)建 store,而不是強(qiáng)迫使用全局狀態(tài),進(jìn)而提高了應(yīng)用的性能和可維護(hù)性。
Zustand 的優(yōu)勢還在于其靈活性。它允許開發(fā)者在不犧牲性能的前提下,使用多種方式管理狀態(tài),包括異步操作、持久化存儲等。同時(shí),Zustand 還支持中間件功能,如 immer 和 devtools,讓狀態(tài)更新變得更加簡潔,并方便開發(fā)和調(diào)試。
在這篇文章中,我們將深入探討 Zustand 的核心概念、使用方法以及它在實(shí)際開發(fā)中的應(yīng)用案例。通過對 Zustand 的全面解析,期望能夠幫助開發(fā)者在構(gòu)建高效、可維護(hù)的 React 應(yīng)用時(shí),更好地利用這一強(qiáng)大的狀態(tài)管理工具。
基本使用
編寫狀態(tài)加方法
import {create} from 'zustand' const useBookStore = create<any>((set,get)=>({ price: 30, total:100, increment(){ set(( state:any ) => ({ total: state.total + 1 })); }, decrement(){ set(( state:any ) => ({ total: Math.max(state.total - 1, 0) })); // 確保total不小于0 }, getTotal(){ return get().price * get().total } })) export default useBookStore
在組件中使用
const Child1 =() => { const price = useBookStore((state:any)=> state.price) const total= useBookStore((state:any)=> state.total) const increment = useBookStore((state:any) => state.increment ) const decrement = useBookStore((state:any) => state.decrement ) const getTotal = useBookStore((state:any)=> state.getTotal) return ( <> <h2>{price}</h2> <h2>{total}</h2> <h2>{getTotal()}</h2> <button onClick={decrement}>decrement</button> <button onClick={increment}>increment</button> </> ) }
異步方法操作
async bookPromotion(){ //使用Promise來模仿異步操作 let rate = await Promise.resolve(0.8); set(( state:any )=>{ state.price *= rate }) }
中間件
immer
簡化不可變狀態(tài)更新 不用每次都返回一個(gè)對象了
import {immer } from 'zustand/middleware/immer' const useBookStore = create<any>()(immer((set,get)=>({ price: 40, total:100, increment(){ set(( state:any ) => { state.total += 1 }); }, decrement(){ set(( state:any ) => { Math.max(state.total -= 1, 0) }); // 確保total不小于0 }, getTotal(){ return get().price * get().total }, async bookPromotion(){ //使用Promise來模仿異步操作 let rate = await Promise.resolve(0.8); set(( state:any )=>{ state.price *= rate }) } }))) export default useBookStore
簡化狀態(tài)獲取
使用解構(gòu)賦值
const { price, total, increment, decrement, getTotal, bookPromotion } = useBookStore((state) => ({ price: state.price, total: state.total, increment: state.increment, decrement: state.decrement, getTotal: state.getTotal, bookPromotion: state.bookPromotion, }));
優(yōu)化性能
Child1
和 Child2
組件都使用了相同的狀態(tài)管理商店(store),這意味著它們會共享相同的狀態(tài)。當(dāng)你在 Child1
中更新狀態(tài)時(shí),Child2
即使store沒有發(fā)生變化也會跟著執(zhí)行,因?yàn)樗鼈兌紡耐粋€(gè) store 中獲取數(shù)據(jù)。這非常浪費(fèi)性能
使用useShallow包裹
import { useShallow } from 'zustand/react/shallow' import useBookStore from './zustand/index.tsx' const Child1 =() => { // const price = useBookStore((state:any)=> state.price) // const total= useBookStore((state:any)=> state.total) const increment = useBookStore((state:any) => state.increment ) const decrement = useBookStore((state:any) => state.decrement ) const getTotal = useBookStore((state:any)=> state.getTotal) const bookPromotion= useBookStore((state:any)=> state.bookPromotion) const {price,total} = useBookStore() return ( <> <h2>{price}</h2> <h2>{total}</h2> <h2>{getTotal()}</h2> <button onClick={decrement}>decrement</button> <button onClick={bookPromotion}>promotion</button> <button onClick={increment}>increment</button> </> ) } const Child2 = () => { const {test} = useBookStore(useShallow((state:any) =>({ test: state.test}))) console.log(1,2,test) return <h2>{test}</h2> }
Redux DevTools插件
import {devtools}from "zustand/middleware" {enable:true,name"bookstore"}
持久化保存
import create from 'zustand'; import { persist } from 'zustand/middleware'; // 創(chuàng)建一個(gè)持久化的 store const useStore = create(persist( (set) => ({ count: 0, increase: () => set((state) => ({ count: state.count + 1 })), decrease: () => set((state) => ({ count: state.count - 1 })), }), { name: ###, // 存儲的 key 名稱 storage: create(()=> sessionStorage), // 可以選擇使用 localStorage 或 sessionStorage partialize:(state) => ({key:value}) } ));
文章到這里就結(jié)束了,希望對你有所幫助。
到此這篇關(guān)于Zustand介紹與使用 React狀態(tài)管理工具的文章就介紹到這了,更多相關(guān)Zustand React狀態(tài)管理工具內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React+CSS?實(shí)現(xiàn)繪制豎狀柱狀圖
這篇文章主要介紹了React+CSS?實(shí)現(xiàn)繪制豎狀柱狀圖,文章圍繞主題展開詳細(xì)的內(nèi)容介紹。具有一定的參考價(jià)值,需要的朋友可以參考一下2022-09-09詳解React中的useMemo和useCallback的區(qū)別
React中的useMemo和useCallback是兩個(gè)重要的Hooks。常常被用于優(yōu)化組件的性能。雖然這兩個(gè)Hooks看起來很相似,但它們彼此之間還是有很大的區(qū)別的,隨著小編一起來學(xué)習(xí)吧2023-04-04解決React報(bào)錯(cuò)Property 'X' does not 
這篇文章主要為大家介紹了解決React報(bào)錯(cuò)Property 'X' does not exist on type 'HTMLElement',有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12React?Hook?Form?優(yōu)雅處理表單使用指南
這篇文章主要為大家介紹了React?Hook?Form?優(yōu)雅處理表單使用指南,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03Native?Memory?Tracking追蹤區(qū)域示例分析
這篇文章主要為大家介紹了Native?Memory?Tracking追蹤區(qū)域示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11