首页  >  文章  >  web前端  >  最简单的状态教程

最简单的状态教程

Patricia Arquette
Patricia Arquette原创
2024-10-03 06:27:30497浏览

Simplest Zustand Tutorial

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn