首頁 > web前端 > js教程 > 主體

最簡單的狀態教程

Patricia Arquette
發布: 2024-10-03 06:27:30
原創
497 人瀏覽過

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!