網站首頁 編程語言 正文
本文主要介紹一種基于 React Hooks 的狀態共享方案,介紹其實現,并總結一下使用感受,目的是在狀態管理方面提供多一種選擇方式。
實現基于 React Hooks 的狀態共享
React 組件間的狀態共享,是一個老生常談的問題,也有很多解決方案,例如 Redux、MobX 等。這些方案很專業,也經歷了時間的考驗,但私以為他們不太適合一些不算復雜的項目,反而會引入一些額外的復雜度。
實際上很多時候,我不想定義 mutation 和 action、我不想套一層 context,更不想寫 connect 和 mapStateToProps;我想要的是一種輕量、簡單的狀態共享方案,簡簡單單引用、簡簡單單使用。
隨著 Hooks 的誕生、流行,我的想法得以如愿。
接著介紹一下我目前在用的方案,將 Hooks 與發布/訂閱模式結合,就能實現一種簡單、實用的狀態共享方案。因為代碼不多,下面將給出完整的實現。
import { Dispatch, SetStateAction, useCallback, useEffect, useReducer, useRef, useState, } from 'react'; /** * @see https://github.com/facebook/react/blob/bb88ce95a87934a655ef842af776c164391131ac/packages/shared/objectIs.js * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x: any, y: any): boolean { return (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y); } const objectIs = typeof Object.is === 'function' ? Object.is : is; /** * @see https://github.com/facebook/react/blob/933880b4544a83ce54c8a47f348effe725a58843/packages/shared/shallowEqual.js * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA: any, objB: any): boolean { if (is(objA, objB)) { return true; } if ( typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null ) { return false; } const keysA = Object.keys(objA); const keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (let i = 0; i < keysA.length; i++) { if ( !Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]]) ) { return false; } } return true; } const useForceUpdate = () => useReducer(() => ({}), {})[1] as VoidFunction; type ISubscriber<T> = (prevState: T, nextState: T) => void; export interface ISharedState<T> { /** 靜態方式獲取數據, 適合在非組件中或者數據無綁定視圖的情況下使用 */ get: () => T; /** 修改數據,賦予新值 */ set: Dispatch<SetStateAction<T>>; /** (淺)合并更新數據 */ update: Dispatch<Partial<T>>; /** hooks方式獲取數據, 適合在組件中使用, 數據變更時會自動重渲染該組件 */ use: () => T; /** 訂閱數據的變更 */ subscribe: (cb: ISubscriber<T>) => () => void; /** 取消訂閱數據的變更 */ unsubscribe: (cb: ISubscriber<T>) => void; /** 篩出部分 state */ usePick<R>(picker: (state: T) => R, deps?: readonly any[]): R; } export type IReadonlyState<T> = Omit<ISharedState<T>, 'set' | 'update'>; /** * 創建不同實例之間可以共享的狀態 * @param initialState 初始數據 */ export const createSharedState = <T>(initialState: T): ISharedState<T> => { let state = initialState; const subscribers: ISubscriber<T>[] = []; // 訂閱 state 的變化 const subscribe = (subscriber: ISubscriber<T>) => { subscribers.push(subscriber); return () => unsubscribe(subscriber); }; // 取消訂閱 state 的變化 const unsubscribe = (subscriber: ISubscriber<T>) => { const index = subscribers.indexOf(subscriber); index > -1 && subscribers.splice(index, 1); }; // 獲取當前最新的 state const get = () => state; // 變更 state const set = (next: SetStateAction<T>) => { const prevState = state; // @ts-ignore const nextState = typeof next === 'function' ? next(prevState) : next; if (objectIs(state, nextState)) { return; } state = nextState; subscribers.forEach((cb) => cb(prevState, state)); }; // 獲取當前最新的 state 的 hooks 用法 const use = () => { const forceUpdate = useForceUpdate(); useEffect(() => { let isMounted = true; // 組件掛載后立即更新一次, 避免無法使用到第一次更新數據 forceUpdate(); const un = subscribe(() => { if (!isMounted) return; forceUpdate(); }); return () => { un(); isMounted = false; }; }, []); return state; }; const usePick = <R>(picker: (s: T) => R, deps = []) => { const ref = useRef<any>({}); ref.current.picker = picker; const [pickedState, setPickedState] = useState<R>(() => ref.current.picker(state), ); ref.current.oldState = pickedState; const sub = useCallback(() => { const pickedOld = ref.current.oldState; const pickedNew = ref.current.picker(state); if (!shallowEqual(pickedOld, pickedNew)) { // 避免 pickedNew 是一個 function setPickedState(() => pickedNew); } }, []); useEffect(() => { const un = subscribe(sub); return un; }, []); useEffect(() => { sub(); }, [...deps]); return pickedState; }; return { get, set, update: (input: Partial<T>) => { set((pre) => ({ ...pre, ...input, })); }, use, subscribe, unsubscribe, usePick, }; };
擁有 createSharedState 之后,下一步就能輕易地創建出一個可共享的狀態了,在組件中使用的方式也很直接。
// 創建一個狀態實例 const countState = createSharedState(0); const A = () => { // 在組件中使用 hooks 方式獲取響應式數據 const count = countState.use(); return <div>A: {count}</div>; }; const B = () => { // 使用 set 方法修改數據 return <button onClick={() => countState.set(count + 1)}>Add</button>; }; const C = () => { return ( <button onClick={() => { // 使用 get 方法獲取數據 console.log(countState.get()); }} > Get </button> ); }; const App = () => { return ( <> <A /> <B /> <C /> </> ); };
對于復雜對象,還提供了一種方式,用于在組件中監聽指定部分的數據變化,避免其他字段變更造成多余的 render:
const complexState = createSharedState({ a: 0, b: { c: 0, }, }); const A = () => { const a = complexState.usePick((state) => state.a); return <div>A: {a}</div>; };
但復雜對象一般更建議使用組合派生的方式,由多個簡單的狀態派生出一個復雜的對象。另外在有些時候,我們會需要一種基于原數據的計算結果,所以這里同時提供了一種派生數據的方式。
通過顯示聲明依賴的方式監聽數據源,再傳入計算函數,那么就能得到一個響應式的派生結果了。
/** * 狀態派生(或 computed) * ```ts * const count1 = createSharedState(1); * const count2 = createSharedState(2); * const count3 = createDerivedState([count1, count2], ([n1, n2]) => n1 + n2); * ``` * @param stores * @param fn * @param initialValue * @returns */ export function createDerivedState<T = any>( stores: IReadonlyState<any>[], fn: (values: any[]) => T, opts?: { /** * 是否同步響應 * @default false */ sync?: boolean; }, ): IReadonlyState<T> & { stop: () => void; } { const { sync } = { sync: false, ...opts }; let values: any[] = stores.map((it) => it.get()); const innerModel = createSharedState<T>(fn(values)); let promise: Promise<void> | null = null; const uns = stores.map((it, i) => { return it.subscribe((_old, newValue) => { values[i] = newValue; if (sync) { innerModel.set(() => fn(values)); return; } // 異步更新 promise = promise || Promise.resolve().then(() => { innerModel.set(() => fn(values)); promise = null; }); }); }); return { get: innerModel.get, use: innerModel.use, subscribe: innerModel.subscribe, unsubscribe: innerModel.unsubscribe, usePick: innerModel.usePick, stop: () => { uns.forEach((un) => un()); }, }; }
至此,基于 Hooks 的狀態共享方的實現介紹就結束了。
在最近的項目中,有需要狀態共享的場景,我都選擇了上述方式,在 Web 項目和小程序 Taro 項目中均能使用同一套實現,一直都比較順利。
使用感受
最后總結一下目前這種方式的幾個特點:
1.實現簡單,不引入其他概念,僅在 Hooks 的基礎上結合發布/訂閱模式,類 React 的場景都能使用,比如 Taro;
2.使用簡單,因為沒有其他概念,直接調用 create 方法即可得到 state 的引用,調用 state 實例上的 use 方法即完成了組件和數據的綁定;
3.類型友好,創建 state 時無需定義多余的類型,使用的時候也能較好地自動推導出類型;
4.避免了 Hooks 的“閉包陷阱”,因為 state 的引用是恒定的,通過 state 的 get 方法總是能獲取到最新的值:
const countState = createSharedState(0); const App = () => { useEffect(() => { setInterval(() => { console.log(countState.get()); }, 1000); }, []); // return ... };
5.直接支持在多個 React 應用之間共享,在使用一些彈框的時候是比較容易出現多個 React 應用的場景:
const countState = createSharedState(0); const Content = () => { const count = countState.use(); return <div>{count}</div>; }; const A = () => ( <button onClick={() => { Dialog.info({ title: 'Alert', content: <Content />, }); }} > open </button> );
6.支持在組件外的場景獲取/更新數據
7.在 SSR 的場景有較大局限性:state 是細碎、分散創建的,而且 state 的生命周期不是跟隨 React 應用,導致無法用同構的方式編寫 SSR 應用代碼
以上,便是本文的全部內容,實際上 Hooks 到目前流行了這么久,社區當中已有不少新型的狀態共享實現方式,這里僅作為一種參考。
根據以上特點,這種方式有明顯的優點,也有致命的缺陷(對于 SSR 而言),但在實際使用中,可以根據具體的情況來選擇合適的方式。比如在 Taro2 的小程序應用中,無需關心 SSR,那么我更傾向于這種方式;如果在 SSR 的同構項目中,那么定還是老老實實選擇 Redux。
總之,是多了一種選擇,到底怎么用還得視具體情況而定。?
原文鏈接:https://webfe.kujiale.com/ji-yu-react-hooks-de-xiao-xing-zhuang-tai-guan-li/
相關推薦
- 2022-07-25 通過底層源碼理解YOLOv5的Backbone_python
- 2023-07-22 Spring的編程式事務TransactionTemplate
- 2021-11-17 Linux配置免密登錄單機和全分布詳細教程_Linux
- 2022-08-19 Git代碼合并之使用 rebase 整理提交歷史
- 2022-12-08 C#與C++?dll之間傳遞字符串string?wchar_t*?char*?IntPtr問題_C#
- 2022-04-04 微信登陸失敗Error: invalid code
- 2022-09-07 如何應用?SOLID?原則在?React?中整理代碼之開閉原則_React
- 2024-03-14 ThreadLocal使用,配合攔截器HandlerInterceptor使用
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支