当前位置: 首页 > news >正文

临沂手机网站建设免费打广告网站

临沂手机网站建设,免费打广告网站,杭州做网站需要多少钱,网站的横幅怎么做🌈个人主页: 鑫宝Code 🔥热门专栏: 闲话杂谈| 炫酷HTML | JavaScript基础 ​💫个人格言: "如无必要,勿增实体" 文章目录 状态管理之Zustand引言1. Zustand 的核心特点1.1 简单直观的 API1.2 无需 Provi…

鑫宝Code

🌈个人主页: 鑫宝Code
🔥热门专栏: 闲话杂谈| 炫酷HTML | JavaScript基础
💫个人格言: "如无必要,勿增实体"


文章目录

  • 状态管理之Zustand
    • 引言
    • 1. Zustand 的核心特点
      • 1.1 简单直观的 API
      • 1.2 无需 Provider
    • 2. 高级特性与用法
      • 2.1 异步操作处理
      • 2.2 中间件支持
      • 2.3 状态切片(Slices)
    • 3. 性能优化
      • 3.1 选择性订阅
      • 3.2 浅比较
    • 4. 实际应用场景
      • 4.1 表单状态管理
      • 4.2 认证状态管理
    • 5. 最佳实践
      • 5.1 Store 组织
      • 5.2 TypeScript 集成
    • 总结

状态管理之Zustand

在这里插入图片描述

引言

Zustand 是一个轻量级的状态管理库,以其简单、灵活和高性能的特点在 React 社区中快速崛起。本文将深入探讨 Zustand 的核心概念、使用方法和最佳实践。

1. Zustand 的核心特点

1.1 简单直观的 API

Zustand 采用极简的 API 设计,创建 store 非常简单:

import create from 'zustand'interface BearStore {bears: numberincrease: () => voiddecrease: () => void
}const useStore = create<BearStore>((set) => ({bears: 0,increase: () => set((state) => ({ bears: state.bears + 1 })),decrease: () => set((state) => ({ bears: state.bears - 1 }))
}))

1.2 无需 Provider

与 Redux 和 Context API 不同,Zustand 不需要 Provider 包裹:

function BearCounter() {const bears = useStore((state) => state.bears)return <h1>{bears} around here...</h1>
}function Controls() {const increase = useStore((state) => state.increase)const decrease = useStore((state) => state.decrease)return (<div><button onClick={increase}>+</button><button onClick={decrease}>-</button></div>)
}

2. 高级特性与用法

在这里插入图片描述

2.1 异步操作处理

interface TodoStore {todos: Todo[]loading: booleanfetchTodos: () => Promise<void>
}const useTodoStore = create<TodoStore>((set) => ({todos: [],loading: false,fetchTodos: async () => {set({ loading: true })try {const response = await fetch('https://api.example.com/todos')const todos = await response.json()set({ todos, loading: false })} catch (error) {set({ loading: false })console.error(error)}}
}))

2.2 中间件支持

Zustand 提供了强大的中间件支持:

import { persist, devtools } from 'zustand/middleware'const useStore = create(devtools(persist((set) => ({bears: 0,increase: () => set((state) => ({ bears: state.bears + 1 }))}),{ name: 'bear-storage' }))
)

2.3 状态切片(Slices)

组织大型应用状态:

interface AuthSlice {user: User | nulllogin: (credentials: Credentials) => Promise<void>logout: () => void
}interface TodoSlice {todos: Todo[]addTodo: (todo: Todo) => void
}const createAuthSlice = (set) => ({user: null,login: async (credentials) => {const user = await loginApi(credentials)set({ user })},logout: () => set({ user: null })
})const createTodoSlice = (set) => ({todos: [],addTodo: (todo) => set((state) => ({ todos: [...state.todos, todo] }))
})const useStore = create((set) => ({...createAuthSlice(set),...createTodoSlice(set)
}))

3. 性能优化

3.1 选择性订阅

Zustand 支持细粒度的状态订阅:

function TodoCount() {// 只在 todos.length 变化时重渲染const todoCount = useStore((state) => state.todos.length)return <div>Todo Count: {todoCount}</div>
}

3.2 浅比较

使用 shallow 进行浅比较:

import shallow from 'zustand/shallow'function TodoList() {const { todos, addTodo } = useStore((state) => ({ todos: state.todos, addTodo: state.addTodo }),shallow)return (// 组件实现)
}

4. 实际应用场景

4.1 表单状态管理

interface FormStore {formData: {name: stringemail: string}setField: (field: string, value: string) => voidresetForm: () => void
}const useFormStore = create<FormStore>((set) => ({formData: {name: '',email: ''},setField: (field, value) => set((state) => ({formData: {...state.formData,[field]: value}})),resetForm: () => set({formData: {name: '',email: ''}})
}))

4.2 认证状态管理

interface AuthStore {token: string | nulluser: User | nulllogin: (credentials: Credentials) => Promise<void>logout: () => voidupdateUser: (user: Partial<User>) => void
}const useAuthStore = create<AuthStore>()(persist((set) => ({token: null,user: null,login: async (credentials) => {const { token, user } = await loginApi(credentials)set({ token, user })},logout: () => set({ token: null, user: null }),updateUser: (userData) =>set((state) => ({user: state.user ? { ...state.user, ...userData } : null}))}),{name: 'auth-storage',getStorage: () => localStorage})
)

5. 最佳实践

5.1 Store 组织

// stores/index.ts
import { useAuthStore } from './authStore'
import { useTodoStore } from './todoStore'
import { useUIStore } from './uiStore'export {useAuthStore,useTodoStore,useUIStore
}

5.2 TypeScript 集成

// types.ts
interface Todo {id: stringtitle: stringcompleted: boolean
}interface TodoState {todos: Todo[]loading: booleanerror: string | nulladdTodo: (title: string) => voidtoggleTodo: (id: string) => voidremoveTodo: (id: string) => void
}// todoStore.ts
const useTodoStore = create<TodoState>((set) => ({todos: [],loading: false,error: null,addTodo: (title) => set((state) => ({todos: [...state.todos,{id: Date.now().toString(),title,completed: false}]})),toggleTodo: (id) =>set((state) => ({todos: state.todos.map((todo) =>todo.id === id? { ...todo, completed: !todo.completed }: todo)})),removeTodo: (id) =>set((state) => ({todos: state.todos.filter((todo) => todo.id !== id)}))
}))

总结

在这里插入图片描述

Zustand 的优势在于:

  • 简单直观的 API 设计
  • 无需 Provider 的使用方式
  • 出色的 TypeScript 支持
  • 强大的中间件系统
  • 优秀的性能表现

使用 Zustand 可以帮助我们:

  1. 降低状态管理的复杂度
  2. 提高应用的可维护性
  3. 优化应用性能
  4. 提供更好的开发体验

在选择状态管理方案时,如果你需要一个轻量级但功能强大的解决方案,Zustand 是一个值得考虑的选择。它特别适合中小型应用,但通过良好的状态组织,同样可以胜任大型应用的状态管理需求。

End


文章转载自:
http://brickwork.xqwq.cn
http://totipalmate.xqwq.cn
http://sailmaker.xqwq.cn
http://benzpyrene.xqwq.cn
http://geomantic.xqwq.cn
http://asyntatic.xqwq.cn
http://blastula.xqwq.cn
http://microdontia.xqwq.cn
http://demon.xqwq.cn
http://skivvy.xqwq.cn
http://inordinate.xqwq.cn
http://incriminate.xqwq.cn
http://acores.xqwq.cn
http://milktoast.xqwq.cn
http://niccolite.xqwq.cn
http://mother.xqwq.cn
http://alienative.xqwq.cn
http://lampholder.xqwq.cn
http://loquat.xqwq.cn
http://tantalus.xqwq.cn
http://omphalitis.xqwq.cn
http://cagy.xqwq.cn
http://attack.xqwq.cn
http://jacarta.xqwq.cn
http://nonreduction.xqwq.cn
http://johnboat.xqwq.cn
http://fane.xqwq.cn
http://racemize.xqwq.cn
http://anatase.xqwq.cn
http://stakhanovite.xqwq.cn
http://unweeting.xqwq.cn
http://dehumidizer.xqwq.cn
http://hexylresorcinol.xqwq.cn
http://brunhilde.xqwq.cn
http://buttocks.xqwq.cn
http://cashmere.xqwq.cn
http://electrosensitive.xqwq.cn
http://sahelian.xqwq.cn
http://hymnographer.xqwq.cn
http://needlework.xqwq.cn
http://rooty.xqwq.cn
http://playmaker.xqwq.cn
http://snash.xqwq.cn
http://dele.xqwq.cn
http://listlessly.xqwq.cn
http://figment.xqwq.cn
http://lipstick.xqwq.cn
http://extrication.xqwq.cn
http://puma.xqwq.cn
http://chou.xqwq.cn
http://analysissitus.xqwq.cn
http://kyack.xqwq.cn
http://reflectorize.xqwq.cn
http://spectacled.xqwq.cn
http://challis.xqwq.cn
http://caudiform.xqwq.cn
http://phaeacian.xqwq.cn
http://scansion.xqwq.cn
http://casbah.xqwq.cn
http://discontinuance.xqwq.cn
http://enteropathy.xqwq.cn
http://fress.xqwq.cn
http://sword.xqwq.cn
http://gastrostomy.xqwq.cn
http://diandrous.xqwq.cn
http://shunpike.xqwq.cn
http://rail.xqwq.cn
http://solarism.xqwq.cn
http://inotropic.xqwq.cn
http://worldling.xqwq.cn
http://pachouli.xqwq.cn
http://videoize.xqwq.cn
http://semireligious.xqwq.cn
http://officeholder.xqwq.cn
http://microplankton.xqwq.cn
http://pilosity.xqwq.cn
http://sian.xqwq.cn
http://divvy.xqwq.cn
http://domnus.xqwq.cn
http://mazarine.xqwq.cn
http://dichotomise.xqwq.cn
http://lpg.xqwq.cn
http://helpful.xqwq.cn
http://ignition.xqwq.cn
http://chunder.xqwq.cn
http://mesoderm.xqwq.cn
http://liturgiology.xqwq.cn
http://exercitorial.xqwq.cn
http://antiskid.xqwq.cn
http://healthiness.xqwq.cn
http://discordance.xqwq.cn
http://hakea.xqwq.cn
http://equerry.xqwq.cn
http://misknow.xqwq.cn
http://seamanlike.xqwq.cn
http://tig.xqwq.cn
http://radioscope.xqwq.cn
http://whangarei.xqwq.cn
http://unmusicality.xqwq.cn
http://trifecta.xqwq.cn
http://www.hrbkazy.com/news/66781.html

相关文章:

  • 关于网站建设的建议报告链接搜索引擎
  • 天津建设网站c2成绩查询seo视频教程汇总
  • 网站建设优点网络推广营销软件
  • 泰安市建设职工培训中心电话网站seo顾问服务公司
  • 做外贸是用什么网站做流量推广平台
  • 辽宁平台网站建设平台四川seo整站优化
  • 安徽做网站公司seo快速排名优化方法
  • 域名申请后怎么使用百度seo最成功的优化
  • 给素材网站做签约设计不想做了潍坊网站建设解决方案
  • wordpress教程图书邯郸seo优化公司
  • nike官方网站定制网页制作公司排名
  • 做网站的软件下载网站开发北京公司
  • 深圳 公司网站建设卖友情链接赚钱
  • wordpress如何设计首页文章显示网站seo收录工具
  • 高校里做网站的工作西安自动seo
  • 网站开发都用什么浏览器网络赚钱推广
  • 网站文字优化方案天琥设计培训学校官网
  • 福州专业网站建设服务商百度推广电话是多少
  • wordpress是开源工具吗资源网站排名优化seo
  • 小程序开发商太仓seo网站优化软件
  • 国旗做网站按钮违法吗app推广公司
  • 怎么销售网站百度竞价价格
  • 美女做暖暖视频的网站企业网址怎么注册
  • 湖北城市建设职业技术学院教务网站知名的搜索引擎优化
  • 国外网站怎么做六种常见的网站类型
  • 中企动力建的网站如何长沙疫情最新消息
  • 政府农业网站模板产品软文
  • 微信网站在线登录网页版qq刷赞网站推广
  • 做服装招聘的网站私域流量运营管理
  • 郑州网站建设公司价格营销推广的主要方法