10. vue pinia 和react redux、jotai对比

发布于:2025-06-06 ⋅ 阅读:(28) ⋅ 点赞:(0)

对比 Vue 的 Pinia,和 React 的 Redux、Jotai,分中英文简要介绍、特性、底层原理、使用场景。

  1. 简单介绍

1.1 Pinia(Vue)
• 英文:Pinia is the official state management library for Vue 3, designed to be simpler and more modular than Vuex.
• 中文:Pinia 是 Vue 3 官方推荐的状态管理库,比 Vuex 更简洁和模块化。

1.2 Redux(React)
• 英文:Redux is a predictable state container for JavaScript apps, widely used in React for managing complex state.
• 中文:Redux 是一个可预测的状态容器,广泛用于 React 中管理复杂状态。

1.3 Jotai(React)
• 英文:Jotai is a primitive and flexible state management library for React, based on atomic state concepts.
• 中文:Jotai 是一个基于原子状态概念的极简灵活状态管理库,专为 React 设计。

  1. 特性对比

2.1 Pinia
• 模块化设计,支持多个 store,状态、getter、action 分明。
• 直接使用响应式 API,语法简洁。
• 支持热重载、Devtools 集成好。
• 类型友好,支持 TypeScript。
• 状态集中管理,方便组件共享。

2.2 Redux
• 中央化状态管理,所有状态集中存储。
• 依赖 action 和 reducer 来修改状态,模式较为严格。
• 有丰富的中间件(middleware)支持异步操作。
• 社区成熟,生态丰富,适合大型复杂项目。
• 需要较多样板代码(boilerplate),学习曲线较陡。

2.3 Jotai
• 极简设计,每个状态是独立的“atom”。
• 免去 reducer、action,直接通过 Hook 操作状态。
• 支持派生状态(类似 computed)和异步状态。
• 细粒度状态更新,性能优异。
• 轻量且灵活,适合中小型项目或追求简洁的场景。

  1. 底层原理简述

3.1 Pinia
• 基于 Vue 3 的响应式系统(Proxy + reactive)。
• Store 中的 state、getter、action 都是响应式对象或函数。
• 利用 Vue 的响应式追踪实现组件自动更新。

3.2 Redux
• 使用单一不可变状态树(single immutable state tree)。
• 通过纯函数 reducer 计算新状态,保证状态不可变。
• 触发 dispatch(action) 更新状态,触发订阅者重新渲染。
• 使用中间件实现异步处理(如 redux-thunk、redux-saga)。

3.3 Jotai
• 状态被封装成独立的 atom,彼此解耦。
• 利用 React 的 Hooks 和 Context 实现状态共享。
• 支持同步和异步 atom,支持状态派生。
• 组件只订阅使用的 atom,减少不必要渲染。

  1. 使用方式简述

4.1 Pinia

import { defineStore } from ‘pinia’

export const useCounterStore = defineStore(‘counter’, {
state: () => ({ count: 0 }),
actions: {
increment() { this.count++ }
}
})

组件中调用:

const counter = useCounterStore()
counter.increment()

4.2 Redux

// 定义 reducer
const counterReducer = (state = { count: 0 }, action) => {
switch(action.type) {
case ‘INCREMENT’: return { count: state.count + 1 }
default: return state
}
}

// 创建 store
const store = createStore(counterReducer)

// 组件中使用
store.dispatch({ type: ‘INCREMENT’ })

通常结合 React-Redux 的 useSelector 和 useDispatch。

4.3 Jotai

import { atom, useAtom } from ‘jotai’

const countAtom = atom(0)

function Counter() {
const [count, setCount] = useAtom(countAtom)
return <button onClick={() => setCount(count + 1)}>{count}
}

  1. 适用场景

5.1 Pinia
• Vue 3 项目,尤其需要模块化和灵活状态管理。
• 中小型到大型项目均适用。
• 需要集成 Devtools,响应式状态管理。

5.2 Redux
• React 大型复杂项目,状态非常集中和共享的应用。
• 需要严格状态管理流程和中间件支持异步任务。
• 需要社区生态丰富的解决方案。

5.3 Jotai
• React 项目,追求极简且灵活的状态管理。
• 组件状态细粒度更新,避免复杂样板代码。
• 中小型项目,或需要原子状态管理的场景。


网站公告

今日签到

点亮在社区的每一天
去签到