40行代碼把Vue3的響應(yīng)式集成進(jìn)React做狀態(tài)管理
前言
vue-next是Vue3的源碼倉庫,Vue3采用lerna做package的劃分,而響應(yīng)式能力@vue/reactivity被劃分到了單獨(dú)的一個(gè)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;
// 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>計(jì)數(shù)器</h1>
<div className="chunk">
<div className="chunk">store中的count現(xiàn)在是 {countState.count}</div>
<div className="chunk">computed值中的plusOne現(xiàn)在是 {countState.plusOne.value}</div>
<Button onClick={mutations.add}>add</Button>
</div>
</Card>
);
}
export default () => {
return (
<Provider value={store}>
<Count />
</Provider>
);
};
可以看出,store的定義只用到了@vue/reactivity,而rxv只是在組件中做了一層橋接,連通了Vue3和React,然后我們就可以盡情的使用Vue3的響應(yīng)式能力啦。
預(yù)覽

可以看到,完美的利用了reactive、computed的強(qiáng)大能力。
分析
從這個(gè)包提供的幾個(gè)核心api來分析:
effect(重點(diǎn))
effect其實(shí)是響應(yīng)式庫中一個(gè)通用的概念:觀察函數(shù),就像Vue2中的Watcher,mobx中的autorun,observer一樣,它的作用是收集依賴。
它接受的是一個(gè)函數(shù),它會(huì)幫你執(zhí)行這個(gè)函數(shù),并且開啟依賴收集,
這個(gè)函數(shù)內(nèi)部對于響應(yīng)式數(shù)據(jù)的訪問都可以收集依賴,那么在響應(yīng)式數(shù)據(jù)被修改后,就會(huì)觸發(fā)更新。
最簡單的用法
const data = reactive({ count: 0 })
effect(() => {
// 就是這句話 訪問了data.count
// 從而收集到了依賴
console.log(data.count)
})
data.count = 1
// 控制臺(tái)打印出1
那么如果把這個(gè)簡單例子中的
() => {
// 就是這句話 訪問了data.count
// 從而收集到了依賴
console.log(data.count)
}
這個(gè)函數(shù),替換成React的組件渲染,是不是就能達(dá)成響應(yīng)式更新組件的目的了?
reactive(重點(diǎn))
響應(yīng)式數(shù)據(jù)的核心api,這個(gè)api返回的是一個(gè)proxy,對上面所有屬性的訪問都會(huì)被劫持,從而在get的時(shí)候收集依賴(也就是正在運(yùn)行的effect),在set的時(shí)候觸發(fā)更新。
ref
對于簡單數(shù)據(jù)類型比如number,我們不可能像這樣去做:
let data = reactive(2) // 😭oops data = 5
這是不符合響應(yīng)式的攔截規(guī)則的,沒有辦法能攔截到data本身的改變,只能攔截到data身上的屬性的改變,所以有了ref。
const data = ref(2) // 💕ok data.value= 5
computed
計(jì)算屬性,依賴值更新以后,它的值也會(huì)隨之自動(dòng)更新。其實(shí)computed內(nèi)部也是一個(gè)effect。
擁有在computed中觀察另一個(gè)computed數(shù)據(jù)、effect觀察computed改變之類的高級特性。
實(shí)現(xiàn)
從這幾個(gè)核心api來看,只要effect能接入到React系統(tǒng)中,那么其他的api都沒什么問題,因?yàn)樗鼈冎皇侨ナ占痚ffect的依賴,去通知effect觸發(fā)更新。
effect接受的是一個(gè)函數(shù),而且effect還支持通過傳入schedule參數(shù)來自定義依賴更新的時(shí)候需要觸發(fā)什么函數(shù),如果我們把這個(gè)schedule替換成對應(yīng)組件的更新呢?要知道在hook的世界中,實(shí)現(xiàn)當(dāng)前組件強(qiáng)制更新可是很簡單的:
useForceUpdate
export const useForceUpdate = () => {
const [, forceUpdate] = useReducer(s => s + 1, 0);
return forceUpdate;
};
這是一個(gè)很經(jīng)典的自定義hook,通過不斷的把狀態(tài)+1來強(qiáng)行讓組件渲染。
而rxv的核心api: useStore接受的也是一個(gè)函數(shù)selector,它會(huì)讓用戶自己選擇在組件中需要訪問的數(shù)據(jù)。
那么思路就顯而易見了:
- 把selector包裝在effect中執(zhí)行,去收集依賴。
- 指定依賴發(fā)生更新時(shí),需要調(diào)用的函數(shù)是當(dāng)前正在使用useStore的這個(gè)組件的forceUpdate強(qiáng)制渲染函數(shù)。
這樣不就實(shí)現(xiàn)了數(shù)據(jù)變化,組件自動(dòng)更新嗎?
簡單的看一下核心實(shí)現(xiàn)
useStore和Provider
import React, { useContext } from 'react';
import { useForceUpdate, useEffection } from './share';
type Selector<T, S> = (store: T) => S;
const StoreContext = React.createContext<any>(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 <Provider>',
);
}
return contextValue;
};
/**
* 在組件中讀取全局狀態(tài)
* 需要通過傳入的函數(shù)收集依賴
*/
export const useStore = <T, S>(selector: Selector<T, S>): 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;
這個(gè)option是傳遞給Vue3的effectapi,
scheduler規(guī)定響應(yīng)式數(shù)據(jù)更新以后應(yīng)該做什么操作,這里我們使用forceUpdate去讓組件重新渲染。
lazy表示延遲執(zhí)行,后面我們手動(dòng)調(diào)用effection來執(zhí)行
{
scheduler: forceUpdate,
lazy: true,
}
再來看下useEffection和useForceUpdate
import { useEffect, useReducer, useRef } from 'react';
import { effect, stop, ReactiveEffect } from '@vue/reactivity';
export const useEffection = (...effectArgs: Parameters<typeof effect>) => {
// 用一個(gè)ref存儲(chǔ)effection
// effect函數(shù)只需要初始化執(zhí)行一遍
const effectionRef = useRef<ReactiveEffect>();
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;
};
也很簡單,就是把傳入的函數(shù)交給effect,并且在組件銷毀的時(shí)候停止effect而已。
流程
- 先通過useForceUpdate在當(dāng)前組件中注冊一個(gè)強(qiáng)制更新的函數(shù)。
- 通過useContext讀取用戶從Provider中傳入的store。
- 再通過Vue的effect去幫我們執(zhí)行selector(store),并且指定scheduler為forceUpdate,這樣就完成了依賴收集。
- 那么在store里的值更新了以后,觸發(fā)了scheduler也就是forceUpdate,我們的React組件就自動(dòng)更新啦。
就簡單的幾行代碼,就實(shí)現(xiàn)了在React中使用@vue/reactivity中的所有能力。
優(yōu)點(diǎn):
- 直接引入@vue/reacivity,完全使用Vue3的reactivity能力,擁有computed, effect等各種能力,并且對于Set和Map也提供了響應(yīng)式的能力。后續(xù)也會(huì)隨著這個(gè)庫的更新變得更加完善的和強(qiáng)大。
- vue-next倉庫內(nèi)部完整的測試用例。
- 完善的TypeScript類型支持。
- 完全復(fù)用@vue/reacivity實(shí)現(xiàn)超強(qiáng)的全局狀態(tài)管理能力。
- 狀態(tài)管理中組件級別的精確更新。
- Vue3總是要學(xué)的嘛,提前學(xué)習(xí)防止失業(yè)!
缺點(diǎn):
由于需要精確的收集依賴全靠useStore,所以selector函數(shù)一定要精確的訪問到你關(guān)心的數(shù)據(jù)。甚至如果你需要觸發(fā)數(shù)組內(nèi)部某個(gè)值的更新,那你在useStore中就不能只返回這個(gè)數(shù)組本身。
舉一個(gè)例子:
function Logger() {
const logs = useStore((store: Store) => {
return store.state.logs.map((log, idx) => (
<p className="log" key={idx}>
{log}
</p>
));
});
return (
<Card hoverable>
<h1>控制臺(tái)</h1>
<div className="logs">{logs}</div>
</Card>
);
}
這段代碼直接在useStore中返回了整段jsx,是因?yàn)閙ap的過程中回去訪問數(shù)組的每一項(xiàng)來收集依賴,只有這樣才能達(dá)到響應(yīng)式的目的。
源碼地址:https://github.com/sl1673495/react-composition-api
到此這篇關(guān)于40行代碼把Vue3的響應(yīng)式集成進(jìn)React做狀態(tài)管理的文章就介紹到這了,更多相關(guān)Vue3 響應(yīng)式集成React狀態(tài)管理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React報(bào)錯(cuò)map()?is?not?a?function詳析
這篇文章主要介紹了React報(bào)錯(cuò)map()?is?not?a?function詳析,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08
react-router-dom入門使用教程(前端路由原理)
這篇文章主要介紹了react-router-dom入門使用教程,主要包括react路由相關(guān)理解,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
react源碼中的生命周期和事件系統(tǒng)實(shí)例解析
這篇文章主要為大家介紹了react源碼中的生命周期和事件系統(tǒng)實(shí)例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
react數(shù)據(jù)管理機(jī)制React.Context源碼解析
這篇文章主要為大家介紹了react數(shù)據(jù)管理機(jī)制React.Context源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11

