PHP前端开发

最简单的状态教程

百变鹏仔 3天前 #JavaScript
文章标签 最简单

zustand 是一个小型、快速且可扩展的 react 状态管理库,可作为 redux 等更复杂解决方案的替代方案。 zustand 获得如此大关注的主要原因是与 redux 相比,它的体积小且语法简单。

了解 zustand 设置

首先,如果您还没有安装 zustand 和 typescript,则需要安装。

npm install zustand'or'yarn add zustand

zustand 提供了一个创建函数来定义您的商店。让我们来看一个存储和操作计数值的基本示例。

让我们创建一个名为 store.ts 的文件,其中我们有一个自定义挂钩 usecounterstore():

import { create } from "zustand"type counterstore = {    count: number    increment: () =&gt; void    resetcount: () =&gt; void}export const usecounterstore = create<counterstore>((set) =&gt; ({    count: 0    increment: () =&gt; set((state) =&gt; ({ count: state.count + 1 })),    resetcount: () =&gt; set({ count: 0 })}))</counterstore>

在此示例中:

在 react 组件中使用 store

import react from 'react'import { usecounterstore } from './store'const counter: react.fc = () =&gt; {  const count = usecounterstore((state) =&gt; state.count) // get count from the store  const increment = usecounterstore((state) =&gt; 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) =&gt; state)

但是这种方法降低了性能。因此,最佳实践是直接访问状态,就像之前显示的那样。

异步操作

在 zustand 中进行异步操作或向服务器调用 api 请求也非常简单。在这里,以下代码说明了一切:

export const usecounterstore = create<counterstore>((set) =&gt; ({    count: 0    increment: () =&gt; set((state) =&gt; ({ count: state.count + 1 })),    incrementasync: async () =&gt; {        await new promise((resolve) =&gt; settimeout(resolve, 1000))        set((state) =&gt; ({ count: state.count + 1 }))    },    resetcount: () =&gt; set({ count: 0 })}))</counterstore>

它看起来不像 javascript 中的通用异步函数吗?首先它运行异步代码,然后用给定值设置状态。

现在,让我们看看如何在 react 组件上使用它:

const othercomponent = ({ count }: { count: number }) =&gt; {  const incrementasync = usecounterstore((state) =&gt; state.incrementasync)  return (    <div>      {count}      <div>        <button onclick="{incrementasync}">increment</button>      </div>    </div>  )}

如何访问react组件外部的状态

到目前为止,您仅访问了 react 组件内的状态。但是从 react 组件外部访问状态又如何呢?是的,使用 zustand,您可以从外部 react 组件访问状态。

const getcount = () =&gt; {  const count = usecounterstore.getstate().count  console.log("count", count)}const othercomponent = ({ count }: { count: number }) =&gt; {  const incrementasync = usecounterstore((state) =&gt; state.incrementasync)  const decrement = usecounterstore((state) =&gt; state.decrement)  useeffect(() =&gt; {    getcount()  }, [])  return (    <div>      {count}      <div>        <button onclick="{incrementasync}">increment</button>        <button onclick="{decrement}">decrement</button>      </div>    </div>  )}

在这里,你可以看到 getcount() 正在通过 getstate() 访问状态

我们也可以设置计数:

const setcount = () =&gt; {  usecounterstore.setstate({ count: 10 })}

持久化中间件

zustand 中的持久中间件用于跨浏览器会话持久保存和补充状态,通常使用 localstoragesessionstorage。此功能允许您即使在页面重新加载后或用户关闭并重新打开浏览器时也能保持状态。以下是其工作原理和使用方法的详细说明。

persist的基本用法

以下是如何使用 persist 设置 zustand 商店:

import create from 'zustand';import { persist } from 'zustand/middleware';// Define the state and actionsinterface BearState {  bears: number;  increase: () =&gt; void;  reset: () =&gt; void;}// Create a store with persist middlewareexport const useStore = create<bearstate>(  persist(    (set) =&gt; ({      bears: 0,      increase: () =&gt; set((state) =&gt; ({ bears: state.bears + 1 })),      reset: () =&gt; set({ bears: 0 }),    }),    {      name: 'bear-storage', // Name of the key in localStorage    }  ));</bearstate>

状态保存在 localstorage 的“bear-storage”键下。现在,即使您刷新页面,熊的数量也会在重新加载后保持不变。

默认情况下,persist 使用 localstorage,但您可以将其更改为 sessionstorage 或任何其他存储系统。关于 zustand 中的持久状态主题,有很多内容需要讨论。您将在这篇文章之后获得有关此主题的详细教程/文章。

结论

我们都知道 redux 作为状态管理工具有多么出色。但 redux 拥有一个有点复杂且庞大的样板。这就是为什么越来越多的开发人员选择 zustand 作为他们的状态管理工具,它简单且可扩展。

但是你仍然会发现 redux 更适合用于非常复杂和嵌套的状态管理。