Zustand介紹與使用 React狀態(tài)管理工具的解決方案

前言
在現(xiàn)代前端開(kāi)發(fā)中,狀態(tài)管理一直是一個(gè)關(guān)鍵的挑戰(zhàn)。隨著應(yīng)用規(guī)模的擴(kuò)大,組件間的狀態(tài)共享變得愈加復(fù)雜。為了應(yīng)對(duì)這一需求,開(kāi)發(fā)者們逐漸尋找更加輕量、靈活的解決方案。在眾多狀態(tài)管理庫(kù)中,Zustand 以其簡(jiǎn)潔易用的特點(diǎn)脫穎而出。
Zustand 是一個(gè)基于 React 的狀態(tài)管理庫(kù),旨在提供簡(jiǎn)單而強(qiáng)大的狀態(tài)管理功能。與傳統(tǒng)的狀態(tài)管理工具相比,Zustand 采用了更為直觀的 API 設(shè)計(jì),降低了學(xué)習(xí)成本,讓開(kāi)發(fā)者能夠快速上手。它的核心理念是“最小化”,意味著你可以只為應(yīng)用中需要的部分狀態(tài)創(chuàng)建 store,而不是強(qiáng)迫使用全局狀態(tài),進(jìn)而提高了應(yīng)用的性能和可維護(hù)性。
Zustand 的優(yōu)勢(shì)還在于其靈活性。它允許開(kāi)發(fā)者在不犧牲性能的前提下,使用多種方式管理狀態(tài),包括異步操作、持久化存儲(chǔ)等。同時(shí),Zustand 還支持中間件功能,如 immer 和 devtools,讓狀態(tài)更新變得更加簡(jiǎn)潔,并方便開(kāi)發(fā)和調(diào)試。
在這篇文章中,我們將深入探討 Zustand 的核心概念、使用方法以及它在實(shí)際開(kāi)發(fā)中的應(yīng)用案例。通過(guò)對(duì) Zustand 的全面解析,期望能夠幫助開(kāi)發(fā)者在構(gòu)建高效、可維護(hù)的 React 應(yīng)用時(shí),更好地利用這一強(qiáng)大的狀態(tài)管理工具。
基本使用
編寫(xiě)狀態(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來(lái)模仿異步操作
let rate = await Promise.resolve(0.8);
set(( state:any )=>{
state.price *= rate
})
}中間件
immer 簡(jiǎn)化不可變狀態(tài)更新 不用每次都返回一個(gè)對(duì)象了
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來(lái)模仿異步操作
let rate = await Promise.resolve(0.8);
set(( state:any )=>{
state.price *= rate
})
}
})))
export default useBookStore簡(jiǎn)化狀態(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),這意味著它們會(huì)共享相同的狀態(tài)。當(dāng)你在 Child1 中更新?tīng)顟B(tài)時(shí),Child2 即使store沒(méi)有發(fā)生變化也會(huì)跟著執(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: ###, // 存儲(chǔ)的 key 名稱(chēng)
storage: create(()=> sessionStorage), // 可以選擇使用 localStorage 或 sessionStorage
partialize:(state) => ({key:value})
}
));文章到這里就結(jié)束了,希望對(duì)你有所幫助。
到此這篇關(guān)于Zustand介紹與使用 React狀態(tài)管理工具的文章就介紹到這了,更多相關(guān)Zustand React狀態(tài)管理工具內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
react component changing uncontrolled in
這篇文章主要為大家介紹了react component changing uncontrolled input報(bào)錯(cuò)解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
React Fiber中面試官最關(guān)心的技術(shù)話題
這篇文章主要為大家介紹了React Fiber中面試官最關(guān)心的技術(shù)話題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
React+Antd 實(shí)現(xiàn)可增刪改表格的示例
這篇文章主要介紹了React+Antd實(shí)現(xiàn)可增刪改表格的示例,幫助大家更好的理解和學(xué)習(xí)使用React,感興趣的朋友可以了解下2021-04-04
前端開(kāi)發(fā)使用Ant Design項(xiàng)目評(píng)價(jià)
這篇文章主要為大家介紹了前端開(kāi)發(fā)使用Ant Design項(xiàng)目評(píng)價(jià),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
React antd tabs切換造成子組件重復(fù)刷新
這篇文章主要介紹了React antd tabs切換造成子組件重復(fù)刷新,需要的朋友可以參考下2021-04-04

