状态管理是现代应用程序开发的一个重要方面,在 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 storeconst 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 locatedconst 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 ( item list ({getitemcount()}) item.id.tostring()} renderitem={({ item }) => ( {item.name}
登录后复制
在此示例中:
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 storeexport 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 storeexport 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-5787https://dev.to/ajmal_hasan/reactotron-setup-in-react-native-redux-applications-4jj3
以上就是使用 Zustand 简化 React Native 中的状态管理的详细内容,更多请关注【创想鸟】其它相关文章!