首頁  >  文章  >  web前端  >  使用 Zustand 簡化 React Native 中的狀態管理

使用 Zustand 簡化 React Native 中的狀態管理

WBOY
WBOY原創
2024-08-31 06:33:06872瀏覽

Simplifying State Management in React Native with Zustand

狀態管理是現代應用程式開發的一個重要方面,在 React Native 中,有效管理狀態可以顯著提高應用程式的效能和可維護性。 Zustand 是 React 的簡約狀態管理函式庫,為處理 React Native 應用程式中的狀態提供了一個優雅而簡單的解決方案。在這篇部落格中,我們將探討 Zustand、它的工作原理以及為什麼它可能是您的 React Native 專案的正確選擇。


祖斯坦是什麼?

Zustand 是一個小型、快速且可擴展的 React 應用程式狀態管理解決方案。它的名稱源自德語中的“國家”一詞,反映了其主要功能:有效管理國家。 Zustand 因其簡單性和易用性而脫穎而出,讓您可以使用最少的樣板程式碼建立狀態儲存。

Zustand的主要特點

  • 最小 API:Zustand 提供了一個簡單的 API,讓狀態管理變得直覺、簡單。
  • 無提供者元件:與其他狀態管理庫不同,Zustand 不需要提供程式元件,這可以簡化您的元件樹。
  • 反應性:Zustand 與 React 的內建鉤子無縫集成,使其反應靈敏且高效。
  • 中間件支援:Zustand 支援中間件以增強功能,例如持久性和日誌記錄。

Zustand 入門

1. 安裝

首先,您需要在 React Native 專案中安裝 Zustand。開啟終端機並運作:

npm install zustand


yarn add zustand

2. 創建商店

Zustand 使用儲存來管理狀態。 store 是一個 JavaScript 對象,它保存狀態並提供更新它的方法。

在 zustand

一套)
目的:更新您商店的狀態。
它是如何運作的:您可以使用它來修改狀態。您提供一個接收當前狀態並傳回新狀態的函數。

b) 得到
目的:讀取商店的目前狀態。
工作原理:您可以使用它來存取當前狀態以進行閱讀或做出決策。

這是建立 Zustand 商店和使用的簡單範例:

myStore1.jsx

import create from 'zustand';

// Create the store
const myStore1 = create((set, get) => ({
    items: [], // Initial state

    // Action to fetch items from an API
    fetchItems: async () => {
        try {
            const response = await fetch('https://api.example.com/items'); // Replace with your API URL
            const data = await response.json();
            set({ items: data });
        } catch (error) {
            console.error('Failed to fetch items:', error);
        }
    },

    // Action to add an item
    addItem: (item) => set((state) => ({
        items: [...state.items, item],
    })),

    // Action to remove an item
    removeItem: (id) => set((state) => ({
        items: state.items.filter(item => item.id !== id),
    })),

    // Action to get the count of items
    getItemCount: () => get().items.length,
}));

export default myStore1;

用法:
應用程式.jsx

import React, { useEffect } from 'react';
import { View, Text, Button, FlatList, StyleSheet } from 'react-native';
import myStore1 from './myStore1'; // Adjust the path to where your store file is located

const App = () => {
    // Destructure actions and state from the store
    const { items, fetchItems, addItem, removeItem, getItemCount } = myStore1();

    // Fetch items when the component mounts
    useEffect(() => {
        fetchItems();
    }, [fetchItems]);

    const handleAddItem = () => {
        const newItem = { id: Date.now(), name: 'New Item' };
        addItem(newItem);
    };

    const handleRemoveItem = (id) => {
        removeItem(id);
    };

    return (
        <View style={styles.container}>
            <Text style={styles.header}>Item List ({getItemCount()})</Text>
            <Button title="Add Item" onPress={handleAddItem} />
            <FlatList
                data={items}
                keyExtractor={(item) => item.id.toString()}
                renderItem={({ item }) => (
                    <View style={styles.item}>
                        <Text>{item.name}</Text>
                        <Button title="Remove" onPress={() => handleRemoveItem(item.id)} />
                    </View>
                )}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 16,
    },
    header: {
        fontSize: 24,
        marginBottom: 16,
    },
    item: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        padding: 16,
        borderBottomWidth: 1,
        borderBottomColor: '#ccc',
    },
});

export default App;

在此範例中:

  • create 是 Zustand 中的一個函數,用來初始化商店。
  • set是Zustand提供的更新商店的功能。
  • count 是由 store 管理的一段狀態。
  • 增加和減少是修改狀態的操作。
  • get是讀取store目前的狀態
  • myStore1 我們使用鉤子來取得目前狀態值和操作函數。

進階用法

1. 中介軟體

Zustand 支援中間件以增強其功能。例如,您可以使用持久性中間件從 AsyncStorage/MMKV 儲存和載入狀態:

a) Zustand 與 React Native 非同步儲存

useScansStore.jsx

import AsyncStorage from '@react-native-async-storage/async-storage';
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';

// Create the store
export const useScansStore = create()(
    persist(
        (set, get) => ({
            fishes: 0, // Initial state
            addAFish: () => set({ fishes: get().fishes + 1 }) // Function to update state
        }),
        {
            name: "food-storage", // Key used to store the data
            storage: createJSONStorage(() => AsyncStorage), // Use AsyncStorage for persistence
        }
    )
);

b) Zustand 與 MMKV

i) 建立mmkv設定檔storage.jsx

import { MMKV } from "react-native-mmkv";

export const storage = new MMKV({
    id: 'my-app-storage',
    encryptionKey: 'some_encryption_key'
})

export const mmkvStorage = {
    setItem: (key, value) => {
        storage.set(key, value)
    },
    getItem: (key) => {
        const value = storage.getString(key)
        return value ?? null
    },
    removeItem: (key) => {
        storage.delete(key)
    },
}

ii)useScansStore.jsx

import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import mmkvStorage from './mmkvStorage'; // Import the MMKV storage configuration

// Create the store
export const useScansStore = create()(
    persist(
        (set, get) => ({
            fishes: 0, // Initial state
            addAFish: () => set({ fishes: get().fishes + 1 }) // Function to update state
        }),
        {
            name: "food-storage", // Key used to store the data
            storage: createJSONStorage(() => mmkvStorage), // Use MMKV for persistence
        }
    )
);

最佳實踐

  • 保持較小的商店:為了保持清晰和簡單,請保持 Zustand 商店集中且較小。如果您的商店變得太大,請考慮將其分成較小的模組化商店。
  • 明智地使用中間件:僅在必要時使用中間件。它會增加複雜性和開銷,因此請根據您的需求進行應用。
  • 利用 React Native 的 Hooks:Zustand 與 React 的 hooks 很好地集成,因此可以利用 useEffect 和 useCallback 等鉤子來管理副作用並優化性能。

結論

Zustand 為 React Native 應用程式中的狀態管理提供了一種簡約且高效的方法。其簡單的 API、反應性和中間件支援使其成為管理小型和大型專案狀態的絕佳選擇。透過遵循本部落格中概述的範例和最佳實踐,您可以將 Zustand 無縫整合到您的 React Native 應用程式中,並享受更乾淨、更可維護的狀態管理解決方案。

相關貼文:
https://dev.to/ajmal_hasan/react-native-mmkv-5787
https://dev.to/ajmal_hasan/reactotron-setup-in-react-native-redux-applications-4jj3

以上是使用 Zustand 簡化 React Native 中的狀態管理的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn