Published on

redux|mobx|vuex|pinia 状态管理

Authors
  • avatar
    Name
    MissTree
    Twitter

redux

redux 是一个用于管理应用程序状态的 JavaScript 库。它提供了一个可预测的状态管理模式,使得应用程序的状态能够以一种可预测的方式发生变化。 Redux 基于 Flux 架构,核心原则包括:

  • 单一数据源:整个应用状态存储在一个 store 中
  • 状态只读:只能通过 dispatch action 来修改
  • 纯函数修改:使用 reducer 函数处理 action Redux 使用不可变数据(immutable data)和纯函数来管理状态变更。

之前有过学习 链接

使用方式

import { createStore } from 'redux';

// 1. 定义 reducer
function counterReducer(state = { count: 0 }, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

// 2. 创建 store
const store = createStore(counterReducer);

// 3. 在React组件中使用
import { useSelector, useDispatch } from 'react-redux';

const Counter = () => {
  const count = useSelector(state => state.count);
  const dispatch = useDispatch();
  
  return (
    <div>
      Count: {count}
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
    </div>
  );
};


// 现代 Redux (Redux Toolkit)
import { createSlice, configureStore } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    incremented: state => { state.value += 1 },
    decremented: state => { state.value -= 1 },
  },
});

const store = configureStore({
  reducer: counterSlice.reducer
});

// 使用方式相同
  • 严格的单向数据流
  • 不可变状态管理
  • 中间件支持(如 redux-thunk, redux-saga)
  • 时间旅行调试
  • 需要更多样板代码(Redux Toolkit 已简化)

mobx

mobx 是一个简单、可扩展的状态管理库,它通过使用响应式编程来管理应用程序的状态。 MobX 采用响应式编程模型,基于观察者模式实现。核心概念包括:

  • Observable state:通过 @observable 或 makeObservable 标记的状态变量
  • Actions:通过 @action 标记的修改状态的方法
  • Computed values:通过 @computed 标记的派生值
  • Reactions:自动响应状态变化的副作用(如 autorun, reaction) MobX 使用 ES6 Proxy(或 defineProperty)来追踪状态访问,自动建立依赖关系图。

使用方式

import { makeObservable, observable, action, computed } from "mobx";

class CounterStore {
  count = 0;

  constructor() {
    makeObservable(this, {
      count: observable,
      increment: action,
      decrement: action,
      double: computed,
    });
  }

  increment = () => this.count++;
  decrement = () => this.count--;

  get double() {
    return this.count * 2;
  }
}

const counterStore = new CounterStore();

// 在React组件中使用
import { observer } from "mobx-react-lite";

const Counter = observer(() => (
  <div>
    Count: {counterStore.count}
    <button onClick={counterStore.increment}>+</button>
    <button onClick={counterStore.decrement}>-</button>
    Double: {counterStore.double}
  </div>
));

特点:

  • 自动追踪依赖,无需手动指定
  • 可变状态(mutable state)
  • 细粒度更新,只有真正依赖变化的组件会重新渲染

react 状态对比

分类优点缺点
MobX细粒度响应,只有依赖特定状态的组件会更新
适合中小型项目
Proxy/defineProperty 有初始性能开销,大型 observable 对象可能变慢
Redux可预测性高,适合大型应用每次 dispatch 会导致所有 connect 的组件检查是否需要更新
Redux Toolkit使用 Immer 内部处理不可变更新,性能与 Redux 类似但开发体验更好-

vuex

vuex 是 vue 官方推荐的状态管理工具,它是一个专为 Vue.js 应用程序开发的状态管理模式。 vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

  • State:单一状态树
  • Getters:基于 state 的计算属性
  • Mutations:同步修改 state 的方法
  • Actions:可包含异步操作,提交 mutations
  • Modules:模块化组织

使用方式

import { createStore } from 'vuex';

const store = createStore({
  state() {
    return { count: 0 };
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    decrement(state) {
      state.count--;
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => commit('increment'), 1000);
    }
  },
  getters: {
    double(state) {
      return state.count * 2;
    }
  }
});

// 在Vue组件中使用
import { useStore } from 'vuex';

export default {
  setup() {
    const store = useStore();
    return {
      count: computed(() => store.state.count),
      double: computed(() => store.getters.double),
      increment: () => store.commit('increment'),
      decrement: () => store.commit('decrement'),
      incrementAsync: () => store.dispatch('incrementAsync')
    };
  }
};

特点:

  • 专为 Vue 设计,深度集成
  • 明确的状态变更流程
  • 支持模块化
  • 相对严格的流程(必须通过 mutations 修改状态)

pinia

pinia 是 vue3 官方推荐的状态管理工具,它是一个轻量级的状态管理库,具有简单易用、类型安全和响应式等特点。 pinia 是一个基于 Vue 3 的状态管理库,它提供了一个简单易用的 API,用于管理应用程序的状态。pinia 支持 Vue 3 的响应式系统,使得状态的变化能够自动触发组件的重新渲染。 Pinia 是 Vuex 的替代品,核心改进:

  • 去掉 mutations,只有 state, getters 和 actions
  • 更好的 TypeScript 支持
  • 组合式 API 优先
  • 多个 store 实例
  • 更轻量级 Pinia 同样基于 Vue 的响应式系统,但设计更简洁。

使用方式

import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
    async incrementAsync() {
      setTimeout(() => this.increment(), 1000);
    }
  }
});

// 在Vue组件中使用
import { useCounterStore } from '@/stores/counter';

export default {
  setup() {
    const counter = useCounterStore();
    return {
      counter,
      count: computed(() => counter.count),
      double: computed(() => counter.double)
    };
  }
};
  • 更简单的 API
  • 更好的 TypeScript 支持
  • 组合式 API 友好
  • 可组合的 stores
  • 没有 mutations,actions 支持同步和异步
  • 自动识别 state 类型
  • 支持 Vue DevTools

vue 状态对比

分类优点缺点
Vuex基于 Vue 响应式系统,性能良好但不如 Pinia 轻量mutations 的严格流程可能增加不必要的复杂性
Pinia更轻量,没有 Vuex 的模块嵌套问题
直接利用 Vue 3 的响应式系统,性能优秀
-