首页 > 其他分享 >使用 Zustand 简化 React Native 中的状态管理

使用 Zustand 简化 React Native 中的状态管理

时间:2024-09-22 08:52:43浏览次数:1  
标签:react Zustand gt items storage zustand React item Native

状态管理是现代应用程序开发的一个重要方面,在 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.jsximport create from 'zustand';// create the storeconst mystore1 = create((set, get) =&gt; ({ items: [], // initial state // action to fetch items from an api fetchitems: async () =&gt; { 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) =&gt; set((state) =&gt; ({ items: [...state.items, item], })), // action to remove an item removeitem: (id) =&gt; set((state) =&gt; ({ items: state.items.filter(item =&gt; item.id !== id), })), // action to get the count of items getitemcount: () =&gt; get().items.length,}));export default mystore1;登录后复制用法:应用程序.jsximport 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 = () =&gt; { // destructure actions and state from the store const { items, fetchitems, additem, removeitem, getitemcount } = mystore1(); // fetch items when the component mounts useeffect(() =&gt; { fetchitems(); }, [fetchitems]); const handleadditem = () =&gt; { const newitem = { id: date.now(), name: 'new item' }; additem(newitem); }; const handleremoveitem = (id) =&gt; { removeitem(id); }; return ( <view style="{styles.container}"><text style="{styles.header}">item list ({getitemcount()})</text><button title="add item" onpress="{handleadditem}"></button> <flatlist data="{items}" keyextractor="{(item)"> item.id.tostring()} renderitem={({ item }) =&gt; ( <view style="{styles.item}"><text>{item.name}</text><button title="remove" onpress="{()"> handleremoveitem(item.id)} /&gt; </button></view> )} /&gt; </flatlist></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.jsximport 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) =&gt; ({ fishes: 0, // initial state addafish: () =&gt; set({ fishes: get().fishes + 1 }) // function to update state }), { name: "food-storage", // key used to store the data storage: createjsonstorage(() =&gt; asyncstorage), // use asyncstorage for persistence } ));登录后复制b) zustand 与 mmkvi) 创建mmkv配置文件storage.jsximport { mmkv } from "react-native-mmkv";export const storage = new mmkv({ id: 'my-app-storage', encryptionkey: 'some_encryption_key'})export const mmkvstorage = { setitem: (key, value) =&gt; { storage.set(key, value) }, getitem: (key) =&gt; { const value = storage.getstring(key) return value ?? null }, removeitem: (key) =&gt; { storage.delete(key) },}登录后复制ii)usescansstore.jsximport { 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) =&gt; ({ fishes: 0, // Initial state addAFish: () =&gt; set({ fishes: get().fishes + 1 }) // Function to update state }), { name: "food-storage", // Key used to store the data storage: createJSONStorage(() =&gt; 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 中的状态管理的详细内容,更多请关注我的其它相关文章!

标签:react,Zustand,gt,items,storage,zustand,React,item,Native
From: https://www.cnblogs.com/aow054/p/18424844

相关文章

  • 使用可重用列表组件扩展 React 应用程序
    在react中构建可扩展的应用程序需要的不仅仅是可靠的业务逻辑。随着应用程序的发展,组件的架构对于其可维护性、性能和灵活性起着重要作用。许多web应用程序中的基本任务之一是处理数据列表。无论是渲染产品列表、表格还是仪表板,您经常会遇到需要可重复和可重用的列表结构的场......
  • 【EasyBlog】基于React+AntD+NextJS+NestJS+MySQL打造的开源博客系统
    Github项目地址:https://github.com/fecommunity/easy-blog,欢迎Star。Easy-BlogEasy-Blog是一套集成文章发表、页面创建、知识库管理、博客后台管理等功能于一体的博客系统。首页-浅色主题首页-暗黑主题文章阅读后台管理✨特性......
  • 什么是反应? Reactjs 概念和术语概述
    什么是react?react是一个javascript库,用于构建用户界面,特别是单页应用程序(spa)。它允许开发人员创建可重用的组件来管理其本地状态并处理用户交互。react遵循单向数据流,这意味着数据从父组件流向子组件,从而促进更好地管理数据和ui状态。关键react术语和概念......
  • 了解 React 的 useMemo:它的作用、何时使用它以及最佳实践
    react是一个用于构建用户界面的强大库,但随着应用程序的增长,您可能会注意到性能有时会成为问题。这就是像usememo这样的reacthook发挥作用的地方。在本文中,我们将深入探讨usememo的作用、何时有用以及使用它的最佳实践。我们还将介绍一些需要避免的常见陷阱。什么是......
  • 了解 React Cache 功能
    随着react生态系统的不断扩大,优化数据获取的更强大的工具之一就是缓存功能。此内置功能允许您执行许多操作,例如有效管理和存储服务器数据、减少冗余网络请求以及提高整体应用程序性能。在本文中,我们将了解react中的缓存功能、它的好处以及如何使用它。什么是react缓存功......
  • Suspense and Fiber- The Intricate Machinery Behind React&#s Rendering Elegance
    reactfiber是react并发渲染的核心,它使框架能够将任务分解为更小的单元,并优先处理更重要的任务,从而实现更流畅、响应更灵敏的用户界面。当与suspense配合使用时,它允许react“暂停”渲染,在等待数据获取或计算等任务完成时显示后备ui。fiber是一个javascript对象,代表rea......
  • Redux 与 ContextProvider:在 React 应用程序中选择状态管理
    长话短说当您需要一个强大且可扩展的解决方案来进行复杂的状态管理时,请使用redux,特别是在具有许多组件与状态交互的大型应用程序中。当你的状态管理需求更简单、更本地化,或者当你想避免小型应用程序中redux的开销时,请使用context.provider。让我们开始吧在react或nex......
  • React 设计模式~布局组件~
    屏幕分割器这种模式经常用于由侧边栏、主栏等组成的常见布局。?app.jsimport{splitscreen}from"./components/split-screen";constleftside=({title})=>{return<h2style="{{"backgroundcolor:>{title}</h2>;};constrightside=({title})=>{......
  • ReactJS 设计模式:编写健壮且可扩展的组件
    reactjs中的设计模式为应用程序开发中的常见问题提供了标准化且经过验证的解决方案。使用这些模式不仅使您的代码更具可读性和可维护性,而且还增强了其可扩展性和健壮性。让我们深入研究一些最流行的reactjs设计模式,并通过示例来说明它们的用法。1.容器和表示组件模式容......
  • Recharts:终极 React 图表库
    在当今数据驱动的世界中,有效可视化数据的能力比以往任何时候都更加重要。无论您是数据科学家、开发人员还是业务分析师,创建富有洞察力的交互式图表都可以帮助您清晰地传达复杂的信息。用于此目的的最佳工具之一是recharts——一个完全基于react组件构建的可组合图表库。在这篇......