欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Hooks封裝與使用示例詳解

 更新時間:2023年01月04日 15:49:06   作者:摸魚的湯姆  
這篇文章主要為大家介紹了Hooks封裝與使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

Hooks是什么?

本篇文章主要介紹Hooks如何在React與Vue3兩大框架中封裝使用。

Hooks就是當(dāng)代碼執(zhí)行在某個執(zhí)行階段,觸發(fā)被鉤子鉤到的事件函數(shù)或者回調(diào)函數(shù),Hooks的概念最早在React的V16.8.0版本正式推出,后面Vue3的出現(xiàn)也引入Hooks的概念,兩者使用Hooks還是會有所差異。

Hooks解決了什么?

  • 完善代碼能力
  • 組件邏輯復(fù)用

HOC與HOOK對比

HOC概念:hoc是React中用于重用組件邏輯的一種高級技術(shù)實現(xiàn)模式,它本身是一個函數(shù),接受一個組件并返回一個新的組件

  • HOC
function Hocomponent(WrappedComponent, selectData) {
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        data: selectData(DataSource, props)
      };
    } 
    render() {
      // ... 并使用新數(shù)據(jù)渲染被包裝的組件!
      return <WrappedComponent data={this.state.data} {...this.props} />;
    }
  };

上邊的例子可以看出高階組件內(nèi)部返回了一個類組件,通過這個類組件對WrappedComponent進(jìn)行包裝,在返回得到一個全新的組件。但是HOC的缺點就是props可能會被覆蓋,而且容易產(chǎn)生嵌套地域。

  • Hooks

react-Hooks的出現(xiàn)主要彌補函數(shù)組件無狀態(tài)無生命周期問題等,主要應(yīng)對class復(fù)雜組件變的難以理解,邏輯混亂,不易拆解和測試與嵌套地域問題。

分別使用React與Vue3兩種框架封裝useThrottle鉤子函數(shù)

  • React實現(xiàn)節(jié)流Hooks
import { useState, useCallback } from "react"; 
export function useThrottleFn(fn, time) {
    let [isTimer,setIsTimer] = useState<any>(null);  
    const clear = () => {
        clearTimeout(isTimer);
        setIsTimer(null) 
    } 
    let throttle = useCallback(()=>{ 
        if (!isTimer) {
            setIsTimer(setTimeout(() => {
                fn()
                clear() 
            }, time)) 
        }
    },[fn, time])
    return [throttle]
}
// 引入使用
  const [throttle] = useThrottleFn((e)=>{
        console.log(e)
    },500)
    const Ceshi  = ()=>{
        let e = 'Hooks'
        throttle(e);
    }

React內(nèi)部也存在很多的Hooks鉤子,常用的鉤子:

useState,useMemo,useCallback,useRef,useContext,但是這些鉤子必須在函數(shù)組件中使用并且在函數(shù)組件中使用鉤子需要在組件頂層調(diào)用,不能在Class中使用。這樣一來讓我們可以揮手告別this.xxx的時代。

  • Vue3實現(xiàn)節(jié)流Hooks
import { ref, unref, watch } from 'vue';
import { useTimeouts } from './useTimeout';
/**
 *
 * @param fn 回調(diào)函數(shù)
 * @param wait 延遲時間
 * @returns
 */
export function useThrottleFn(fn, wait = 80) {
  if (typeof fn !== 'function') {
    return;
  }
  let Timer: any = null;  
  const isReady = ref<Boolean>(false);
  const clearun = () => {
    Timer && clearTimeout(Timer);
  };
  // 閉包實現(xiàn)節(jié)流封裝   
  return function () {
    const _this = this;
    const args = arguments;
    // 更改狀態(tài)觸發(fā)watch監(jiān)聽,觸發(fā)回調(diào)函數(shù)fn
    const startFun = function () {
      isReady.value = true;
    };
    // 這里利用watch監(jiān)聽isReady的狀態(tài)變化執(zhí)行回到函數(shù),而不是直接將回調(diào)函數(shù)放在定時器中
    watch(
      () => unref(isReady),
      () => {
        if (unref(isReady) && Timer) {
          fn.apply(_this, args);
          isReady.value = false;
          Timer = null;
          clearun();
        }
      },
    );
    // Timer 如果不存在就開始執(zhí)行
    if (!Timer) {
      Timer = setTimeout(startFun, wait);
    }
  };
}
// 引入使用
const Ceshi = useThrottleFn(()=>{
      console.log('Hooks')
},300)

Vue3的發(fā)布隨之帶來了很多新特性比如從選項式API到組合式API,引入Hooks等。那這里在介紹一個新的工具庫Vueuse,Vueuse 基于Vue-demi封裝了大量的鉤子工具函數(shù),比如useDark,useToggle其他點擊Vueuse文檔查看更多,并且在Vue2與Vue3都可以使用。當(dāng)然我們也可以自己自定義按需求封裝Hooks,但在Vue3中使用Hooks需要在setup中使用,由setup作為組合式API的入口點,在Vue2使用需要安裝VueCompositionApi進(jìn)行使用。

總結(jié)

React Hooks不能在循環(huán)與嵌套函數(shù)中使用,Vue3可以在嵌套中使用,所以這兩框架的使用或封裝方式是不同的,但是百變不離其宗,兩種鉤子的本質(zhì)是沒有變化的,以上就是Hooks封裝與使用示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Hooks封裝使用的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論