前言
React的状态管理是一个缤纷繁杂的大世界,光我知道的就不下数十种,其中有最出名immutable阵营的redux
,有mutable阵营的mobx
,react-easy-state
,在hooks诞生后还有极简主义的unstated-next
,有蚂蚁金服的大佬出品的hox
、hoox
。
其实社区诞生这么多种状态管理框架,也说明状态管理库之间都有一些让人不满足的地方。
rxv
是我依据这些痛点,并且直接引入了Vue3的package: @vue/reactivity
去做的一个React状态管理框架,下面先看一个简单的示例:
示例
// store.ts
import { reactive, computed, effect } from '@vue/reactivity';
export const state = reactive({
count: 0,
});
const plusOne = computed(() => state.count + 1);
effect(() => {
console.log('plusOne changed: ', plusOne);
});
const add = () => (state.count += 1);
export const mutations = {
// mutation
add,
};
export const store = {
state,
computed: {
plusOne,
},
};
export type Store = typeof store;
// Index.tsx
import { Provider, useStore } from 'rxv'
import { mutations, store, Store } from './store.ts'
function Count() {
const countState = useStore((store: Store) => {
const { state, computed } = store;
const { count } = state;
const { plusOne } = computed;
return {
count,
plusOne,
};
});
return (
<Card hoverable style={
{ marginBottom: 24 }}>
<h1>计数器</h1