
zustand 是一个小型、快速且可扩展的 react 状态管理库,可作为 redux 等更复杂解决方案的替代方案。 zustand 获得如此大关注的主要原因是与 redux 相比,它的体积小且语法简单。
首先,如果您还没有安装 zustand 和 typescript,则需要安装。
npm install zustand 'or' yarn add zustand
zustand 提供了一个创建函数来定义您的商店。让我们来看一个存储和操作计数值的基本示例。
让我们创建一个名为 store.ts 的文件,其中我们有一个自定义挂钩 usecounterstore():
import { create } from "zustand"
type counterstore = {
count: number
increment: () => void
resetcount: () => void
}
export const usecounterstore = create<counterstore>((set) => ({
count: 0
increment: () => set((state) => ({ count: state.count + 1 })),
resetcount: () => set({ count: 0 })
}))
在此示例中:
计数是一个状态。
increasecount和resetcount是修改状态的操作。
set是zustand提供的更新商店的功能。
import react from 'react'
import { usecounterstore } from './store'
const counter: react.fc = () => {
const count = usecounterstore((state) => state.count) // get count from the store
const increment = usecounterstore((state) => state.increment) // get the action
return (
<div>
<h1>{count}</h1>
<button onclick={increment}>increase count</button>
</div>
)
}
export default counter;
这里,counter 是一个 react 组件。如您所见,usecounterstate() 用于访问计数和增量。
您可以解构状态,而不是像下面这样直接获取它们:
const {count, increment} = usecounterstore((state) => state)
但是这种方法降低了性能。因此,最佳实践是直接访问状态,就像之前显示的那样。
在 zustand 中进行异步操作或向服务器调用 api 请求也非常简单。在这里,以下代码说明了一切:
export const usecounterstore = create<counterstore>((set) => ({
count: 0
increment: () => set((state) => ({ count: state.count + 1 })),
incrementasync: async () => {
await new promise((resolve) => settimeout(resolve, 1000))
set((state) => ({ count: state.count + 1 }))
},
resetcount: () => set({ count: 0 })
}))
它看起来不像 javascript 中的通用异步函数吗?首先它运行异步代码,然后用给定值设置状态。
现在,让我们看看如何在 react 组件上使用它:
const othercomponent = ({ count }: { count: number }) => {
const incrementasync = usecounterstore((state) => state.incrementasync)
return (
<div>
{count}
<div>
<button onclick={incrementasync}>increment</button>
</div>
</div>
)
}
到目前为止,您仅访问了 react 组件内的状态。但是从 react 组件外部访问状态又如何呢?是的,使用 zustand,您可以从外部 react 组件访问状态。
const getcount = () => {
const count = usecounterstore.getstate().count
console.log("count", count)
}
const othercomponent = ({ count }: { count: number }) => {
const incrementasync = usecounterstore((state) => state.incrementasync)
const decrement = usecounterstore((state) => state.decrement)
useeffect(() => {
getcount()
}, [])
return (
<div>
{count}
<div>
<button onclick={incrementasync}>increment</button>
<button onclick={decrement}>decrement</button>
</div>
</div>
)
}
在这里,你可以看到 getcount() 正在通过 getstate() 访问状态
我们也可以设置计数:
const setcount = () => {
usecounterstore.setstate({ count: 10 })
}
zustand 中的持久中间件用于跨浏览器会话持久保存和补充状态,通常使用 localstorage 或 sessionstorage。此功能允许您即使在页面重新加载后或用户关闭并重新打开浏览器时也能保持状态。以下是其工作原理和使用方法的详细说明。
以下是如何使用 persist 设置 zustand 商店:
import create from 'zustand';
import { persist } from 'zustand/middleware';
// Define the state and actions
interface BearState {
bears: number;
increase: () => void;
reset: () => void;
}
// Create a store with persist middleware
export const useStore = create<BearState>(
persist(
(set) => ({
bears: 0,
increase: () => set((state) => ({ bears: state.bears + 1 })),
reset: () => set({ bears: 0 }),
}),
{
name: 'bear-storage', // Name of the key in localStorage
}
)
);
状态保存在 localstorage 的“bear-storage”键下。现在,即使您刷新页面,熊的数量也会在重新加载后保持不变。
默认情况下,persist 使用 localstorage,但您可以将其更改为 sessionstorage 或任何其他存储系统。关于 zustand 中的持久状态主题,有很多内容需要讨论。您将在这篇文章之后获得有关此主题的详细教程/文章。
我们都知道 redux 作为状态管理工具有多么出色。但 redux 拥有一个有点复杂且庞大的样板。这就是为什么越来越多的开发人员选择 zustand 作为他们的状态管理工具,它简单且可扩展。
但是你仍然会发现 redux 更适合用于非常复杂和嵌套的状态管理。
以上就是最简单的状态教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号