自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

「React進(jìn)階」只用兩個(gè)自定義 Hooks 就能替代 React-Redux ?

開發(fā) 前端
之前有朋友問我,React Hooks 能否解決 React 項(xiàng)目狀態(tài)管理的問題。這個(gè)問題讓我思索了很久,最后得出的結(jié)論是:能,不過需要兩個(gè)自定義 hooks 去實(shí)現(xiàn)。那么具體如何實(shí)現(xiàn)的呢?那就是今天要講的內(nèi)容了。

[[413016]]

本文轉(zhuǎn)載自微信公眾號(hào)「前端Sharing」,作者前端Sharing。轉(zhuǎn)載本文請聯(lián)系前端Sharing公眾號(hào)。

前言

之前有朋友問我,React Hooks 能否解決 React 項(xiàng)目狀態(tài)管理的問題。這個(gè)問題讓我思索了很久,最后得出的結(jié)論是:能,不過需要兩個(gè)自定義 hooks 去實(shí)現(xiàn)。那么具體如何實(shí)現(xiàn)的呢?那就是今天要講的內(nèi)容了。

通過本文,你能夠?qū)W習(xí)以下內(nèi)容:

  • useContext ,useRef ,useMemo,useEffect 的基本用法。
  • 如何將不同組件的自定義 hooks 建立通信,共享狀態(tài)。
  • 合理編寫自定義 hooks , 分析 hooks 之間的依賴關(guān)系。
  • 自定義 hooks 編寫過程中一些細(xì)節(jié)問題。

帶著如上的知識(shí)點(diǎn),開啟閱讀之旅吧~

一 設(shè)計(jì)思路

首先,看一下要實(shí)現(xiàn)的兩個(gè)自定義 hooks 具體功能。

  • useCreateStore 用于產(chǎn)生一個(gè)狀態(tài) Store ,通過 context 上下文傳遞 ,為了讓每一個(gè)自定義 hooks useConnect 都能獲取 context 里面的狀態(tài)屬性。
  • useConnect 使用這個(gè)自定義 hooks 的組件,可以獲取改變狀態(tài)的 dispatch 方法,還可以訂閱 state ,被訂閱的 state 發(fā)生變化,組件更新。

如何讓不同組件的自定義 hooks 共享狀態(tài)并實(shí)現(xiàn)通信呢?

首先不同組件的自定義 hooks ,可以通過 useContext 獲得共有狀態(tài),而且還需要實(shí)現(xiàn)狀態(tài)管理和組件通信,那么就需要一個(gè)狀態(tài)調(diào)度中心來統(tǒng)一做這些事,可以稱之為 ReduxHooksStore ,它具體做的事情如下:

  • 全局管理 state, state 變化,通知對應(yīng)組件更新。
  • 收集使用 useConnect 組件的信息。組件銷毀還要清除這些信息。
  • 維護(hù)并傳遞負(fù)責(zé)更新的 dispatch 方法。
  • 一些重要 api 要暴露給 context 上下文,傳遞給每一個(gè) useConnect。

1 useCreateStore 設(shè)計(jì)

首先 useCreateStore 是在靠近根部組件的位置的, 而且全局只需要一個(gè),目的就是創(chuàng)建一個(gè) Store ,并通過 Provider 傳遞下去。

使用:

  1. const store = useCreateStore( reducer , initState ) 

參數(shù):

  • reducer :全局 reducer,純函數(shù),傳入 state 和 action ,返回新的 state 。
  • initState :初始化 state 。

返回值:為 store 暴露的主要功能函數(shù)。

2 Store設(shè)計(jì)

Store 為上述所說的調(diào)度中心,接收全局 reducer ,內(nèi)部維護(hù)狀態(tài) state ,負(fù)責(zé)通知更新 ,收集用 useConnect 的組件。

  1. const Store = new ReduxHooksStore(reducer,initState).exportStore() 

參數(shù):接收兩個(gè)參數(shù),透傳 useCreateStore 的參數(shù)。

3 useConnect設(shè)計(jì)

使用 useConnect 的組件,將獲得 dispatch 函數(shù),用于更新 state ,還可以通過第一個(gè)參數(shù)訂閱 state ,被訂閱的 state 改變 ,會(huì)讓組件更新。

  1. // 訂閱 state 中的 number  
  2. const mapStoreToState = (state)=>({ number: state.number  }) 
  3. const [ state , dispatch ] = useConnect(mapStoreToState) 

參數(shù):

  • mapStoreToState:將 Store 中 state ,映射到組件的 state 中,可以做視圖渲染使用。
  • 如果沒有第一個(gè)參數(shù),那么只提供 dispatch 函數(shù),不會(huì)訂閱 state 變化帶來的更新。

返回值:返回值是一個(gè)數(shù)組。

  • 數(shù)組第一項(xiàng):為映射的 state 的值。
  • 數(shù)組第二項(xiàng):為改變 state 的 dispatch 函數(shù)。

4 原理圖

二 useCreateStore

  1. export const ReduxContext = React.createContext(null
  2. /* 用于產(chǎn)生 reduxHooks 的 store */ 
  3. export function useCreateStore(reducer,initState){ 
  4.    const store = React.useRef(null
  5.    /* 如果存在——不需要重新實(shí)例化 Store */ 
  6.    if(!store.current){ 
  7.        store.current  = new ReduxHooksStore(reducer,initState).exportStore() 
  8.    } 
  9.    return store.current 

useCreateStore 主要做的是:

  • 接收 reducer 和 initState ,通過 ReduxHooksStore 產(chǎn)生一個(gè) store ,不期望把 store 全部暴露給使用者,只需要暴露核心的方法,所以調(diào)用實(shí)例下的 exportStore抽離出核心方法。
  • 使用一個(gè) useRef 保存核心方法,傳遞給 Provider 。

三 狀態(tài)管理者 —— ReduxHooksStore

接下來看一下核心狀態(tài) ReduxHooksStore 。

  1. import { unstable_batchedUpdates } from 'react-dom' 
  2. class ReduxHooksStore { 
  3.     constructor(reducer,initState){ 
  4.        this.name = '__ReduxHooksStore__' 
  5.        this.id = 0 
  6.        this.reducer = reducer 
  7.        this.state = initState 
  8.        this.mapConnects = {} 
  9.     } 
  10.     /* 需要對外傳遞的接口 */ 
  11.     exportStore=()=>{ 
  12.         return { 
  13.             dispatch:this.dispatch.bind(this), 
  14.             subscribe:this.subscribe.bind(this), 
  15.             unSubscribe:this.unSubscribe.bind(this), 
  16.             getInitState:this.getInitState.bind(this) 
  17.         } 
  18.     } 
  19.     /* 獲取初始化 state */ 
  20.     getInitState=(mapStoreToState)=>{ 
  21.         return mapStoreToState(this.state) 
  22.     } 
  23.     /* 更新需要更新的組件 */ 
  24.     publicRender=()=>{ 
  25.         unstable_batchedUpdates(()=>{ /* 批量更新 */ 
  26.             Object.keys(this.mapConnects).forEach(name=>{ 
  27.                 const { update } = this.mapConnects[name
  28.                 update(this.state) 
  29.             }) 
  30.         }) 
  31.     } 
  32.     /* 更新 state  */ 
  33.     dispatch=(action)=>{ 
  34.        this.state = this.reducer(this.state,action
  35.        // 批量更新 
  36.        this.publicRender() 
  37.     } 
  38.     /* 注冊每個(gè) connect  */ 
  39.     subscribe=(connectCurrent)=>{ 
  40.         const connectName = this.name + (++this.id) 
  41.         this.mapConnects[connectName] =  connectCurrent 
  42.         return connectName 
  43.     } 
  44.     /* 解除綁定 */ 
  45.     unSubscribe=(connectName)=>{ 
  46.         delete this.mapConnects[connectName] 
  47.     } 

狀態(tài)

  • reducer:這個(gè) reducer 為全局的 reducer ,由 useCreateStore 傳入。
  • state:全局保存的狀態(tài) state ,每次執(zhí)行 reducer 會(huì)得到新的 state 。
  • mapConnects:里面保存每一個(gè) useConnect 組件的更新函數(shù)。用于派發(fā) state 改變帶來的更新。

方法

負(fù)責(zé)初始化:

  • getInitState:這個(gè)方法給自定義 hooks 的 useConnect 使用,用于獲取初始化的 state 。
  • exportStore:這個(gè)方法用于把 ReduxHooksStore 提供的核心方法傳遞給每一個(gè) useConnect 。

負(fù)責(zé)綁定|解綁:

  • subscribe:綁定每一個(gè)自定義 hooks useConnect 。
  • unSubscribe:解除綁定每一個(gè) hooks 。

負(fù)責(zé)更新:

  • dispatch:這個(gè)方法提供給業(yè)務(wù)組件層,每一個(gè)使用 useConnect 的組件可以通過 dispatch 方法改變 state ,內(nèi)部原理是通過調(diào)用 reducer 產(chǎn)生一個(gè)新的 state 。
  • publicRender:當(dāng) state 改變需要通知每一個(gè)使用 useConnect 的組件,這個(gè)方法就是通知更新,至于組件需不需要更新,那是 useConnect 內(nèi)部需要處理的事情,這里還有一個(gè)細(xì)節(jié),就是考慮到 dispatch 的觸發(fā)場景可以是異步狀態(tài)下,所以用 React-DOM 中 unstable_batchedUpdates 開啟批量更新原則。

四 useConnect

useConnect 是整個(gè)功能的核心部分,它要做的事情是獲取最新的 state ,然后通過訂閱函數(shù) mapStoreToState 得到訂閱的 state ,判斷訂閱的 state 是否發(fā)生變化。如果發(fā)生變化渲染最新的 state 。

  1. export function useConnect(mapStoreToState=()=>{}){ 
  2.     /* 獲取 Store 內(nèi)部的重要函數(shù) */ 
  3.    const contextValue = React.useContext(ReduxContext) 
  4.    const { getInitState , subscribe ,unSubscribe , dispatch } = contextValue 
  5.    /* 用于傳遞給業(yè)務(wù)組件的 state  */ 
  6.    const stateValue = React.useRef(getInitState(mapStoreToState)) 
  7.  
  8.    /* 渲染函數(shù) */ 
  9.    const [ , forceUpdate ] = React.useState() 
  10.    /* 產(chǎn)生 */ 
  11.    const connectValue = React.useMemo(()=>{ 
  12.        const state =  { 
  13.            /* 用于比較一次 dispatch 中,新的 state 和 之前的state 是否發(fā)生變化  */ 
  14.            cacheState: stateValue.current
  15.            /* 更新函數(shù) */ 
  16.            update:function (newState) { 
  17.                /* 獲取訂閱的 state */ 
  18.                const selectState = mapStoreToState(newState) 
  19.                /* 淺比較 state 是否發(fā)生變化,如果發(fā)生變化, */ 
  20.                const isEqual = shallowEqual(state.cacheState,selectState) 
  21.                state.cacheState = selectState 
  22.                stateValue.current  = selectState 
  23.                if(!isEqual){ 
  24.                    /* 更新 */ 
  25.                    forceUpdate({}) 
  26.                } 
  27.            } 
  28.        } 
  29.        return state 
  30.    },[ contextValue ]) // 將 contextValue 作為依賴項(xiàng)。 
  31.  
  32.    React.useEffect(()=>{ 
  33.        /* 組件掛載——注冊 connect */ 
  34.        const name =  subscribe(connectValue) 
  35.        return function (){ 
  36.             /* 組件卸載 —— 解綁 connect */ 
  37.            unSubscribe(name
  38.        } 
  39.    },[ connectValue ]) /* 將 connectValue 作為 useEffect 的依賴項(xiàng) */ 
  40.  
  41.    return [ stateValue.current , dispatch ] 

初始化

  • 用 useContext 獲取上下文中, ReduxHooksStore 提供的核心函數(shù)。
  • 用 useRef 來保存得到的最新的 state 。
  • 用 useState 產(chǎn)生一個(gè)更新函數(shù) forceUpdate ,這個(gè)函數(shù)只是更新組件。

注冊|解綁流程

  • 注冊:通過 useEffect 來向 ReduxHooksStore 中注冊當(dāng)前 useConnect 產(chǎn)生的 connectValue ,connectValue 是什么馬上會(huì)講到。subscribe 用于注冊,會(huì)返回當(dāng)前 connectValue 的唯一標(biāo)識(shí) name 。
  • 解綁:在 useEffect 的銷毀函數(shù)中,可以用調(diào)用 unSubscribe 傳入 name 來解綁當(dāng)前的 connectValue

connectValue是否更新組件

  • connectValue :真正地向 ReduxHooksStore 注冊的狀態(tài),首先用 useMemo 來對 connectValue 做緩存,connectValue 為一個(gè)對象,里面的 cacheState 保留了上一次的 mapStoreToState 產(chǎn)生的 state ,還有一個(gè)負(fù)責(zé)更新的 update 函數(shù)。
  • 更新流程 :當(dāng)觸發(fā) dispatch 在 ReduxHooksStore 中,會(huì)讓每一個(gè) connectValue 的 update 都執(zhí)行, update 會(huì)觸發(fā)映射函數(shù) mapStoreToState 來得到當(dāng)前組件想要的 state 內(nèi)容。然后通過 shallowEqual 淺比較新老 state 是否發(fā)生變化,如果發(fā)生變化,那么更新組件。完成整個(gè)流程。
  • shallowEqual :這個(gè)淺比較就是 React 里面的淺比較,在第 11 章已經(jīng)講了其流程,這里就不講了。

分清依賴關(guān)系

  • 首先自定義 hooks useConnect 的依賴關(guān)系是上下文 contextValue 改變,那么說明 store 發(fā)生變化,所以重新通過 useMemo 產(chǎn)生新的 connectValue 。所以 useMemo 依賴 contextValue。
  • connectValue 改變,那么需要解除原來的綁定關(guān)系,重新綁定。useEffect 依賴 connectValue。

局限性

整個(gè) useConnect 有一些局限性,比如:

  • 沒有考慮 mapStoreToState 可變性,無法動(dòng)態(tài)傳入 mapStoreToState 。
  • 淺比較,不能深層次比較引用數(shù)據(jù)類型。

五 使用與驗(yàn)證效果

接下來就是驗(yàn)證效果環(huán)節(jié),我模擬了組件通信的場景。

根部組件注入 Store

  1. import { ReduxContext , useConnect , useCreateStore } from './hooks/useRedux' 
  2. function  Index(){ 
  3.     const [ isShow , setShow ] =  React.useState(true
  4.     console.log('index 渲染'
  5.     return <div> 
  6.         <CompA /> 
  7.         <CompB /> 
  8.         <CompC /> 
  9.         {isShow &&  <CompD />} 
  10.         <button onClick={() => setShow(!isShow)} >點(diǎn)擊</button> 
  11.     </div> 
  12.  
  13. function Root(){ 
  14.     const store = useCreateStore(function(state,action){ 
  15.         const { type , payload } =action 
  16.         if(type === 'setA' ){ 
  17.             return { 
  18.                 ...state, 
  19.                 mesA:payload 
  20.             } 
  21.         }else if(type === 'setB'){ 
  22.             return { 
  23.                 ...state, 
  24.                 mesB:payload 
  25.             } 
  26.         }else if(type === 'clear'){ //清空 
  27.             return  { mesA:'',mesB:'' } 
  28.         } 
  29.         else
  30.             return state 
  31.         } 
  32.     }, 
  33.     { mesA:'111',mesB:'111' }) 
  34.     return <div> 
  35.         <ReduxContext.Provider value={store} > 
  36.             <Index/> 
  37.         </ReduxContext.Provider> 
  38.     </div> 

Root根組件

  • 通過 useCreateStore 創(chuàng)建一個(gè) store ,傳入 reducer 和 初始化的值 { mesA:'111',mesB:'111' }
  • 用 Provider 傳遞 store。

Index組件

  • 有四個(gè)子組件 CompA , CompB ,CompC ,CompD 。其中 CompD 是 動(dòng)態(tài)掛載的。

業(yè)務(wù)組件使用

  1. function CompA(){ 
  2.     const [ value ,setValue ] = useState(''
  3.     const [state ,dispatch ] = useConnect((state)=> ({ mesB : state.mesB }) ) 
  4.     return <div className="component_box" > 
  5.         <p> 組件A</p> 
  6.         <p>組件B對我說 : {state.mesB} </p> 
  7.         <input onChange={(e)=>setValue(e.target.value)} 
  8.             placeholder="對B組件說" 
  9.         /> 
  10.         <button onClick={()=> dispatch({ type:'setA' ,payload:value })} >確定</button> 
  11.     </div> 
  12.  
  13. function CompB(){ 
  14.     const [ value ,setValue ] = useState(''
  15.     const [state ,dispatch ] = useConnect((state)=> ({ mesA : state.mesA }) ) 
  16.     return <div className="component_box" > 
  17.         <p> 組件B</p> 
  18.         <p>組件A對我說 : {state.mesA} </p> 
  19.         <input onChange={(e)=>setValue(e.target.value)} 
  20.             placeholder="對A組件說" 
  21.         /> 
  22.         <button onClick={()=> dispatch({ type:'setB' ,payload:value })} >確定</button> 
  23.     </div> 
  24.  
  25. function CompC(){ 
  26.     const [state  ] = useConnect((state)=> ({ mes1 : state.mesA,mes2 : state.mesB }) ) 
  27.     return <div className="component_box" > 
  28.         <p>組件A : {state.mes1} </p> 
  29.         <p>組件B : {state.mes2} </p> 
  30.     </div> 
  31.  
  32. function CompD(){ 
  33.     const [ ,dispatch  ] = useConnect( ) 
  34.     console.log('D 組件更新'
  35.     return <div className="component_box" > 
  36.         <button onClick={()=> dispatch({ type:'clear' })} > 清空 </button> 
  37.     </div> 
  • CompA 和 CompB 模擬組件雙向通信。
  • CompC 組件接收 CompA 和 CompB 通信內(nèi)容,并映射到 mes1 ,mes2 屬性上。
  • CompD 沒有 mapStoreToState ,沒有訂閱 state ,state 變化組件不會(huì)更新,只是用 dispatch 清空狀態(tài)。

效果

六 總結(jié)

本文通過兩個(gè)自定義 hooks 實(shí)現(xiàn)了 React-Redux 的基本功能,這個(gè)模式在真實(shí)項(xiàng)目中可以使用嗎?我覺得如果是小型項(xiàng)目,是完全可以使用的,對于大型項(xiàng)目還是用 React Redux 或者其他成熟的狀態(tài)管理工具。

 

責(zé)任編輯:武曉燕 來源: 前端Sharing
相關(guān)推薦

2020-10-23 09:26:57

React-Redux

2022-06-06 09:28:36

ReactHook

2020-06-12 08:22:27

React ReduxReact開發(fā)

2021-09-28 09:00:00

開發(fā)JavaScript存儲(chǔ)

2021-08-14 08:45:27

React開發(fā)應(yīng)用程序

2019-08-20 15:16:26

Reacthooks前端

2025-03-05 00:00:00

ReactstoreUI 更新

2025-03-05 00:00:00

state變更組件

2017-06-20 12:48:55

React Nativ自定義模塊Note.js

2021-03-18 08:00:55

組件Hooks React

2023-11-06 08:00:00

ReactJavaScript開發(fā)

2020-08-10 06:31:01

React Hooks前端開發(fā)

2019-03-13 10:10:26

React組件前端

2024-06-13 09:50:45

2023-03-14 07:23:48

ReactJSX語法

2010-09-01 08:35:07

Visual Stud

2022-06-23 09:04:14

ReactHooks項(xiàng)目

2021-03-09 09:52:55

技術(shù)React Hooks'數(shù)據(jù)

2022-03-31 17:54:29

ReactHooks前端

2022-08-21 09:41:42

ReactVue3前端
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)