」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 最簡單的狀態教程

最簡單的狀態教程

發佈於2024-11-09
瀏覽:743

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((set) => ({
    count: 0
    increment: () => set((state) => ({ count: state.count   1 })),
    resetCount: () => set({ count: 0 })
}))

在此範例中:

  • count 是個狀態。

  • 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 (
    

{count}

) } export default Counter;

這裡,Counter 是一個 React 元件。可以看到,useCounterState()用於存取計數和增量。

您可以解構狀態,而不是像下面這樣直接獲取它們:

const {count, increment} = useCounterStore((state) => state)

但是這種方法降低了效能。因此,最佳實踐是直接存取狀態,就像之前顯示的那樣。

非同步操作

在 Zustand 中進行非同步操作或向伺服器呼叫 API 請求也非常簡單。在這裡,下面的程式碼解釋了一切:

export const useCounterStore = create((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 (
    
{count}
) }

如何存取 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 (
    
{count}
) }

這裡可以看到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(
  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 更推薦用於非常複雜和嵌套的狀態管理。

版本聲明 本文轉載於:https://dev.to/abeertech01/simplest-zustand-tutorial-28a8?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3