前言
前言前言vue-next是Vue3的源码仓库,Vue3采用lerna做package的划分,而响应式能力@vue/reactivity被划分到了单独的一个package中。
如果我们想把它集成到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;
// 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 (


计数器





store中的count现在是 {countState.count}


computed值中的plusOne现在是 {countState.plusOne.value}






);
}

export default () => {
return (




);
};
// 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 (


计数器





store中的count现在是 {countState.count}


computed值中的plusOne现在是 {countState.plusOne.value}






);
}

export default () => {
return (




);
};可以看出,store的定义只用到了@vue/reactivity,而rxv只是在组件中做了一层桥接,连通了Vue3和React,然后我们就可以尽情的使用Vue3的响应式能力啦。
预览预览预览可以看到,完美的利用了reactive、computed的强大能力。
分析
分析分析从这个包提供的几个核心api来分析:
effect(重点)
effect(重点)effect其实是响应式库中一个通用的概念:观察函数,就像Vue2中的Watcher,mobx中的autorun,observer一样,它的作用是收集依赖。
它接受的是一个函数,它会帮你执行这个函数,并且开启依赖收集,
这个函数内部对于响应式数据的访问都可以收集依赖,那么在响应式数据被修改后,就会触发更新。
最简单的用法

const data = reactive({ count: 0 })
effect(() => {
// 就是这句话 访问了data.count
// 从而收集到了依赖
console.log(data.count)
})

data.count = 1
// 控制台打印出1


const data = reactive({ count: 0 })
effect(() => {
// 就是这句话 访问了data.count
// 从而收集到了依赖
console.log(data.count)
})

data.count = 1
// 控制台打印出1

那么如果把这个简单例子中的

() => {
// 就是这句话 访问了data.count
// 从而收集到了依赖
console.log(data.count)
}

() => {
// 就是这句话 访问了data.count
// 从而收集到了依赖
console.log(data.count)
}
这个函数,替换成React的组件渲染,是不是就能达成响应式更新组件的目的了?
reactive(重点)
reactive(重点)响应式数据的核心api,这个api返回的是一个proxy,对上面所有属性的访问都会被劫持,从而在get的时候收集依赖(也就是正在运行的effect),在set的时候触发更新。
ref
ref对于简单数据类型比如number,我们不可能像这样去做:

let data = reactive(2)
// oops
data = 5
let data = reactive(2)
// oops
data = 5这是不符合响应式的拦截规则的,没有办法能拦截到data本身的改变,只能拦截到data身上的属性的改变,所以有了ref。

const data = ref(2)
// ok
data.value= 5

const data = ref(2)
// ok
data.value= 5
computed
computed计算属性,依赖值更新以后,它的值也会随之自动更新。其实computed内部也是一个effect。
拥有在computed中观察另一个computed数据、effect观察computed改变之类的高级特性。
实现
实现实现从这几个核心api来看,只要effect能接入到React系统中,那么其他的api都没什么问题,因为它们只是去收集effect的依赖,去通知effect触发更新。
effect接受的是一个函数,而且effect还支持通过传入schedule参数来自定义依赖更新的时候需要触发什么函数,如果我们把这个schedule替换成对应组件的更新呢?要知道在hook的世界中,实现当前组件强制更新可是很简单的:
useForceUpdate
export const useForceUpdate = () => {
const [, forceUpdate] = useReducer(s => s + 1, 0);
return forceUpdate;
};

export const useForceUpdate = () => {
const [, forceUpdate] = useReducer(s => s + 1, 0);
return forceUpdate;
};
这是一个很经典的自定义hook,通过不断的把状态+1来强行让组件渲染。
而rxv的核心api: useStore接受的也是一个函数selector,它会让用户自己选择在组件中需要访问的数据。
那么思路就显而易见了:

把selector包装在effect中执行,去收集依赖。

指定依赖发生更新时,需要调用的函数是当前正在使用useStore的这个组件的forceUpdate强制渲染函数。
把selector包装在effect中执行,去收集依赖。指定依赖发生更新时,需要调用的函数是当前正在使用useStore的这个组件的forceUpdate强制渲染函数。这样不就实现了数据变化,组件自动更新吗?
简单的看一下核心实现
useStore和Provider
useStore和Provider
import React, { useContext } from 'react';
import { useForceUpdate, useEffection } from './share';

type Selector = (store: T) => S;

const StoreContext = React.createContext(null);

const useStoreContext = () => {
const contextValue = useContext(StoreContext);
if (!contextValue) {
throw new Error(

'could not find store context value; please ensure the component is wrapped in a ',
);
}
return contextValue;
};

/**
* 在组件中读取全局状态
* 需要通过传入的函数收集依赖
*/
export const useStore = (selector: Selector): S => {
const forceUpdate = useForceUpdate();
const store = useStoreContext();

const effection = useEffection(() => selector(store), {
scheduler: forceUpdate,
lazy: true,
});

const value = effection();
return value;
};

export const Provider = StoreContext.Provider;
import React, { useContext } from 'react';
import { useForceUpdate, useEffection } from './share';

type Selector = (store: T) => S;

const StoreContext = React.createContext(null);

const useStoreContext = () => {
const contextValue = useContext(StoreContext);
if (!contextValue) {
throw new Error(

'could not find store context value; please ensure the component is wrapped in a ',
);
}
return contextValue;
};

/**
* 在组件中读取全局状态
* 需要通过传入的函数收集依赖
*/
export const useStore = (selector: Selector): S => {
const forceUpdate = useForceUpdate();
const store = useStoreContext();

const effection = useEffection(() => selector(store), {
scheduler: forceUpdate,
lazy: true,
});

const value = effection();
return value;
};

export const Provider = StoreContext.Provider;这个option是传递给Vue3的effectapi,
scheduler规定响应式数据更新以后应该做什么操作,这里我们使用forceUpdate去让组件重新渲染。
lazy表示延迟执行,后面我们手动调用effection来执行
{
scheduler: forceUpdate,
lazy: true,
}

{
scheduler: forceUpdate,
lazy: true,
}
再来看下useEffection和useForceUpdate

import { useEffect, useReducer, useRef } from 'react';
import { effect, stop, ReactiveEffect } from '@vue/reactivity';

export const useEffection = (...effectArgs: Parameters) => {
// 用一个ref存储effection
// effect函数只需要初始化执行一遍
const effectionRef = useRef();
if (!effectionRef.current) {
effectionRef.current = effect(...effectArgs);
}

// 卸载组件后取消effect
const stopEffect = () => {
stop(effectionRef.current!);
};
useEffect(() => stopEffect, []);

return effectionRef.current
};

export const useForceUpdate = () => {
const [, forceUpdate] = useReducer(s => s + 1, 0);
return forceUpdate;
};


import { useEffect, useReducer, useRef } from 'react';
import { effect, stop, ReactiveEffect } from '@vue/reactivity';

export const useEffection = (...effectArgs: Parameters) => {
// 用一个ref存储effection
// effect函数只需要初始化执行一遍
const effectionRef = useRef();
if (!effectionRef.current) {
effectionRef.current = effect(...effectArgs);
}

// 卸载组件后取消effect
const stopEffect = () => {
stop(effectionRef.current!);
};
useEffect(() => stopEffect, []);

return effectionRef.current
};

export const useForceUpdate = () => {
const [, forceUpdate] = useReducer(s => s + 1, 0);
return forceUpdate;
};

也很简单,就是把传入的函数交给effect,并且在组件销毁的时候停止effect而已。
流程流程流程

先通过useForceUpdate在当前组件中注册一个强制更新的函数。

通过useContext读取用户从Provider中传入的store。

再通过Vue的effect去帮我们执行selector(store),并且指定scheduler为forceUpdate,这样就完成了依赖收集。

那么在store里的值更新了以后,触发了scheduler也就是forceUpdate,我们的React组件就自动更新啦。
先通过useForceUpdate在当前组件中注册一个强制更新的函数。通过useContext读取用户从Provider中传入的store。再通过Vue的effect去帮我们执行selector(store),并且指定scheduler为forceUpdate,这样就完成了依赖收集。那么在store里的值更新了以后,触发了scheduler也就是forceUpdate,我们的React组件就自动更新啦。就简单的几行代码,就实现了在React中使用@vue/reactivity中的所有能力。
优点:优点:优点:

直接引入@vue/reacivity,完全使用Vue3的reactivity能力,拥有computed, effect等各种能力,并且对于Set和Map也提供了响应式的能力。后续也会随着这个库的更新变得更加完善的和强大。

vue-next仓库内部完整的测试用例。

完善的TypeScript类型支持。

完全复用@vue/reacivity实现超强的全局状态管理能力。

状态管理中组件级别的精确更新。

Vue3总是要学的嘛,提前学习防止失业!
直接引入@vue/reacivity,完全使用Vue3的reactivity能力,拥有computed, effect等各种能力,并且对于Set和Map也提供了响应式的能力。后续也会随着这个库的更新变得更加完善的和强大。vue-next仓库内部完整的测试用例。完善的TypeScript类型支持。完全复用@vue/reacivity实现超强的全局状态管理能力。状态管理中组件级别的精确更新。Vue3总是要学的嘛,提前学习防止失业!缺点:缺点:缺点:由于需要精确的收集依赖全靠useStore,所以selector函数一定要精确的访问到你关心的数据。甚至如果你需要触发数组内部某个值的更新,那你在useStore中就不能只返回这个数组本身。举一个例子:

function Logger() {
const logs = useStore((store: Store) => {
return store.state.logs.map((log, idx) => (



{log}


));
});

return (


控制台



{logs}


);
}
function Logger() {
const logs = useStore((store: Store) => {
return store.state.logs.map((log, idx) => (



{log}


));
});

return (


控制台



{logs}


);
}这段代码直接在useStore中返回了整段jsx,是因为map的过程中回去访问数组的每一项来收集依赖,只有这样才能达到响应式的目的。
源码地址:https://github.com/sl1673495/react-composition-apihttps://github.com/sl1673495/react-composition-api