本文參考原文-http://bjbsair.com/2020-03-22/tech-info/2095.html
前言
vue-next是Vue3的源碼倉庫,Vue3采用lerna做package的劃分,而響應(yīng)式能力@vue/reactivity被劃分到了單獨(dú)的一個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;
復(fù)制代碼
// 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>計數(shù)器</h1>
<div class>
<div class>store中的count現(xiàn)在是 {countState.count}</div>
<div class>computed值中的plusOne現(xiàn)在是 {countState.plusOne.value}</div>
<Button onClick={mutations.add}>add</Button>
</div>
</Card>
);
}
export default () => {
return (
<Provider value={store}>
<Count />
</Provider>
);
};
復(fù)制代碼
可以看出睁壁,store的定義只用到了@vue/reactivity行剂,而rxv只是在組件中做了一層橋接,連通了Vue3和React铲觉,然后我們就可以盡情的使用Vue3的響應(yīng)式能力啦。
預(yù)覽
可以看到,完美的利用了reactive撕贞、computed的強(qiáng)大能力。
分析
從這個包提供的幾個核心api來分析:
effect(重點(diǎn))
effect其實是響應(yīng)式庫中一個通用的概念:觀察函數(shù),就像Vue2中的Watcher链快,mobx中的autorun,observer一樣,它的作用是收集依賴。
它接受的是一個函數(shù)奔穿,它會幫你執(zhí)行這個函數(shù),并且開啟依賴收集,
這個函數(shù)內(nèi)部對于響應(yīng)式數(shù)據(jù)的訪問都可以收集依賴彩倚,那么在響應(yīng)式數(shù)據(jù)被修改后结澄,就會觸發(fā)更新们妥。
最簡單的用法
const data = reactive({ count: 0 })
effect(() => {
// 就是這句話 訪問了data.count
// 從而收集到了依賴
console.log(data.count)
})
data.count = 1
// 控制臺打印出1
復(fù)制代碼
那么如果把這個簡單例子中的
() => {
// 就是這句話 訪問了data.count
// 從而收集到了依賴
console.log(data.count)
}
復(fù)制代碼
這個函數(shù)旅赢,替換成React的組件渲染,是不是就能達(dá)成響應(yīng)式更新組件的目的了?
reactive(重點(diǎn))
響應(yīng)式數(shù)據(jù)的核心api养渴,這個api返回的是一個proxy翘紊,對上面所有屬性的訪問都會被劫持,從而在get的時候收集依賴(也就是正在運(yùn)行的effect),在set的時候觸發(fā)更新坏瘩。
ref
對于簡單數(shù)據(jù)類型比如number柬脸,我們不可能像這樣去做:
let data = reactive(2)
// oops
data = 5
復(fù)制代碼
這是不符合響應(yīng)式的攔截規(guī)則的倒堕,沒有辦法能攔截到data本身的改變爆价,只能攔截到data身上的屬性的改變,所以有了ref蛾号。
const data = ref(2)
// ok
data.value= 5
復(fù)制代碼
computed
計算屬性鲜结,依賴值更新以后精刷,它的值也會隨之自動更新怒允。其實computed內(nèi)部也是一個effect锈遥。
擁有在computed中觀察另一個computed數(shù)據(jù)所灸、effect觀察computed改變之類的高級特性爬立。
實現(xiàn)
從這幾個核心api來看侠驯,只要effect能接入到React系統(tǒng)中,那么其他的api都沒什么問題儒士,因為它們只是去收集effect的依賴着撩,去通知effect觸發(fā)更新睹酌。
effect接受的是一個函數(shù)憋沿,而且effect還支持通過傳入schedule參數(shù)來自定義依賴更新的時候需要觸發(fā)什么函數(shù)辐啄,如果我們把這個schedule替換成對應(yīng)組件的更新呢?要知道在hook的世界中壶辜,實現(xiàn)當(dāng)前組件強(qiáng)制更新可是很簡單的:
useForceUpdate
export const useForceUpdate = () => {
const [, forceUpdate] = useReducer(s => s + 1, 0);
return forceUpdate;
};
復(fù)制代碼
這是一個很經(jīng)典的自定義hook悯舟,通過不斷的把狀態(tài)+1來強(qiáng)行讓組件渲染。
而rxv的核心api: useStore接受的也是一個函數(shù)selector砸民,它會讓用戶自己選擇在組件中需要訪問的數(shù)據(jù)抵怎。
那么思路就顯而易見了:
- 把selector包裝在effect中執(zhí)行,去收集依賴岭参。
- 指定依賴發(fā)生更新時反惕,需要調(diào)用的函數(shù)是當(dāng)前正在使用useStore的這個組件的forceUpdate強(qiáng)制渲染函數(shù)演侯。
這樣不就實現(xiàn)了數(shù)據(jù)變化姿染,組件自動更新嗎?
簡單的看一下核心實現(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;
復(fù)制代碼
這個option是傳遞給Vue3的effectapi秒际,
scheduler規(guī)定響應(yīng)式數(shù)據(jù)更新以后應(yīng)該做什么操作悬赏,這里我們使用forceUpdate去讓組件重新渲染。
lazy表示延遲執(zhí)行娄徊,后面我們手動調(diào)用effection來執(zhí)行
{
scheduler: forceUpdate,
lazy: true,
}
復(fù)制代碼
再來看下useEffection和useForceUpdate
import { useEffect, useReducer, useRef } from 'react';
import { effect, stop, ReactiveEffect } from '@vue/reactivity';
export const useEffection = (...effectArgs: Parameters<typeof effect>) => {
// 用一個ref存儲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;
};
復(fù)制代碼
也很簡單闽颇,就是把傳入的函數(shù)交給effect,并且在組件銷毀的時候停止effect而已嵌莉。
流程
- 先通過useForceUpdate在當(dāng)前組件中注冊一個強(qiáng)制更新的函數(shù)进萄。
- 通過useContext讀取用戶從Provider中傳入的store捻脖。
- 再通過Vue的effect去幫我們執(zhí)行selector(store)锐峭,并且指定scheduler為forceUpdate,這樣就完成了依賴收集可婶。
- 那么在store里的值更新了以后沿癞,觸發(fā)了scheduler也就是forceUpdate,我們的React組件就自動更新啦矛渴。
就簡單的幾行代碼椎扬,就實現(xiàn)了在React中使用@vue/reactivity中的所有能力。
優(yōu)點(diǎn):
- 直接引入@vue/reacivity具温,完全使用Vue3的reactivity能力蚕涤,擁有computed, effect等各種能力,并且對于Set和Map也提供了響應(yīng)式的能力铣猩。后續(xù)也會隨著這個庫的更新變得更加完善的和強(qiáng)大揖铜。
- vue-next倉庫內(nèi)部完整的測試用例。
- 完善的TypeScript類型支持达皿。
- 完全復(fù)用@vue/reacivity實現(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)部某個值的更新物邑,那你在useStore中就不能只返回這個數(shù)組本身溜哮。
舉一個例子:
function Logger() {
const logs = useStore((store: Store) => {
return store.state.logs.map((log, idx) => (
<p class key={idx}>
{log}
</p>
));
});
return (
<Card hoverable>
<h1>控制臺</h1>
<div class>{logs}</div>
</Card>
);
}
復(fù)制代碼
這段代碼直接在useStore中返回了整段jsx,是因為map的過程中回去訪問數(shù)組的每一項來收集依賴色解,只有這樣才能達(dá)到響應(yīng)式的目的茬射。
本文參考原文-http://bjbsair.com/2020-03-22/tech-info/2095/
前言
vue-next是Vue3的源碼倉庫,Vue3采用lerna做package的劃分冒签,而響應(yīng)式能力@vue/reactivity被劃分到了單獨(dú)的一個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;
復(fù)制代碼
// 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>計數(shù)器</h1>
<div class>
<div class>store中的count現(xiàn)在是 {countState.count}</div>
<div class>computed值中的plusOne現(xiàn)在是 {countState.plusOne.value}</div>
<Button onClick={mutations.add}>add</Button>
</div>
</Card>
);
}
export default () => {
return (
<Provider value={store}>
<Count />
</Provider>
);
};
復(fù)制代碼
可以看出朴读,store的定義只用到了@vue/reactivity,而rxv只是在組件中做了一層橋接走趋,連通了Vue3和React衅金,然后我們就可以盡情的使用Vue3的響應(yīng)式能力啦。
預(yù)覽
可以看到簿煌,完美的利用了reactive氮唯、computed的強(qiáng)大能力。
分析
從這個包提供的幾個核心api來分析:
effect(重點(diǎn))
effect其實是響應(yīng)式庫中一個通用的概念:觀察函數(shù)姨伟,就像Vue2中的Watcher惩琉,mobx中的autorun,observer一樣夺荒,它的作用是收集依賴瞒渠。
它接受的是一個函數(shù),它會幫你執(zhí)行這個函數(shù)技扼,并且開啟依賴收集伍玖,
這個函數(shù)內(nèi)部對于響應(yīng)式數(shù)據(jù)的訪問都可以收集依賴,那么在響應(yīng)式數(shù)據(jù)被修改后剿吻,就會觸發(fā)更新窍箍。
最簡單的用法
const data = reactive({ count: 0 })
effect(() => {
// 就是這句話 訪問了data.count
// 從而收集到了依賴
console.log(data.count)
})
data.count = 1
// 控制臺打印出1
復(fù)制代碼
那么如果把這個簡單例子中的
() => {
// 就是這句話 訪問了data.count
// 從而收集到了依賴
console.log(data.count)
}
復(fù)制代碼
這個函數(shù),替換成React的組件渲染,是不是就能達(dá)成響應(yīng)式更新組件的目的了仔燕?
reactive(重點(diǎn))
響應(yīng)式數(shù)據(jù)的核心api造垛,這個api返回的是一個proxy,對上面所有屬性的訪問都會被劫持晰搀,從而在get的時候收集依賴(也就是正在運(yùn)行的effect)五辽,在set的時候觸發(fā)更新。
ref
對于簡單數(shù)據(jù)類型比如number外恕,我們不可能像這樣去做:
let data = reactive(2)
// oops
data = 5
復(fù)制代碼
這是不符合響應(yīng)式的攔截規(guī)則的杆逗,沒有辦法能攔截到data本身的改變,只能攔截到data身上的屬性的改變鳞疲,所以有了ref罪郊。
const data = ref(2)
// ok
data.value= 5
復(fù)制代碼
computed
計算屬性,依賴值更新以后尚洽,它的值也會隨之自動更新悔橄。其實computed內(nèi)部也是一個effect。
擁有在computed中觀察另一個computed數(shù)據(jù)腺毫、effect觀察computed改變之類的高級特性癣疟。
實現(xiàn)
從這幾個核心api來看,只要effect能接入到React系統(tǒng)中潮酒,那么其他的api都沒什么問題睛挚,因為它們只是去收集effect的依賴,去通知effect觸發(fā)更新急黎。
effect接受的是一個函數(shù)扎狱,而且effect還支持通過傳入schedule參數(shù)來自定義依賴更新的時候需要觸發(fā)什么函數(shù),如果我們把這個schedule替換成對應(yīng)組件的更新呢勃教?要知道在hook的世界中淤击,實現(xiàn)當(dāng)前組件強(qiáng)制更新可是很簡單的:
useForceUpdate
export const useForceUpdate = () => {
const [, forceUpdate] = useReducer(s => s + 1, 0);
return forceUpdate;
};
復(fù)制代碼
這是一個很經(jīng)典的自定義hook,通過不斷的把狀態(tài)+1來強(qiáng)行讓組件渲染荣回。
而rxv的核心api: useStore接受的也是一個函數(shù)selector遭贸,它會讓用戶自己選擇在組件中需要訪問的數(shù)據(jù)。
那么思路就顯而易見了:
- 把selector包裝在effect中執(zhí)行心软,去收集依賴。
- 指定依賴發(fā)生更新時著蛙,需要調(diào)用的函數(shù)是當(dāng)前正在使用useStore的這個組件的forceUpdate強(qiáng)制渲染函數(shù)删铃。
這樣不就實現(xiàn)了數(shù)據(jù)變化,組件自動更新嗎踏堡?
簡單的看一下核心實現(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;
復(fù)制代碼
這個option是傳遞給Vue3的effectapi猎唁,
scheduler規(guī)定響應(yīng)式數(shù)據(jù)更新以后應(yīng)該做什么操作,這里我們使用forceUpdate去讓組件重新渲染顷蟆。
lazy表示延遲執(zhí)行诫隅,后面我們手動調(diào)用effection來執(zhí)行
{
scheduler: forceUpdate,
lazy: true,
}
復(fù)制代碼
再來看下useEffection和useForceUpdate
import { useEffect, useReducer, useRef } from 'react';
import { effect, stop, ReactiveEffect } from '@vue/reactivity';
export const useEffection = (...effectArgs: Parameters<typeof effect>) => {
// 用一個ref存儲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;
};
復(fù)制代碼
也很簡單腐魂,就是把傳入的函數(shù)交給effect,并且在組件銷毀的時候停止effect而已逐纬。
流程
- 先通過useForceUpdate在當(dāng)前組件中注冊一個強(qiáng)制更新的函數(shù)蛔屹。
- 通過useContext讀取用戶從Provider中傳入的store。
- 再通過Vue的effect去幫我們執(zhí)行selector(store)豁生,并且指定scheduler為forceUpdate兔毒,這樣就完成了依賴收集。
- 那么在store里的值更新了以后甸箱,觸發(fā)了scheduler也就是forceUpdate育叁,我們的React組件就自動更新啦。
就簡單的幾行代碼芍殖,就實現(xiàn)了在React中使用@vue/reactivity中的所有能力豪嗽。
優(yōu)點(diǎn):
- 直接引入@vue/reacivity,完全使用Vue3的reactivity能力豌骏,擁有computed, effect等各種能力昵骤,并且對于Set和Map也提供了響應(yīng)式的能力。后續(xù)也會隨著這個庫的更新變得更加完善的和強(qiáng)大肯适。
- vue-next倉庫內(nèi)部完整的測試用例变秦。
- 完善的TypeScript類型支持。
- 完全復(fù)用@vue/reacivity實現(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)部某個值的更新纬凤,那你在useStore中就不能只返回這個數(shù)組本身福贞。
舉一個例子:
function Logger() {
const logs = useStore((store: Store) => {
return store.state.logs.map((log, idx) => (
<p class key={idx}>
{log}
</p>
));
});
return (
<Card hoverable>
<h1>控制臺</h1>
<div class>{logs}</div>
</Card>
);
}
復(fù)制代碼
這段代碼直接在useStore中返回了整段jsx,是因為map的過程中回去訪問數(shù)組的每一項來收集依賴停士,只有這樣才能達(dá)到響應(yīng)式的目的挖帘。