首页 > web前端 > js教程 > 正文

最简单的状态教程

聖光之護
发布: 2024-10-05 19:36:25
转载
896人浏览过

最简单的状态教程

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: () => 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提供的更新商店的功能。

在 react 组件中使用 store

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

persist的基本用法

以下是如何使用 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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号