React Hook基本使用

2022-08-19 06:15:13 字數 1411 閱讀 8859

簡單說一下為什麼我會了解到hook api吧。之前寫react只會用class元件的方法,但是新專案使用到了hook,然後被迫學習這個api。

為什麼要使用hook?

根據官方文件介紹:hook是react16.8的新增特性。它可以讓你在不編寫class的情況下使用state以及其他的react特性。

effect hook

了解這個api之前先弄懂兩個名詞「***」與「作用」。其實他們是等同的是 你之前在使用react元件中執行過資料獲取、訂閱或者手動修改過的操作。

useeffect就是乙個effect hook,給函式元件增加了操作***的能力。它與class元件中的componentdidmount、componentdidupdat和componentwillunmount作用相同。只是被合成了乙個api。

使用:

import react,  from 'react';

function demo() times';

}) ;

return (

you clicked times

setcount(count + 1)}>

click me

)}

當你呼叫useeffect時。就是告訴react在完成對dom的更改後執行你的'***'函式。

但是上面這個demo存在乙個問題。就是頁面會一直呼叫usereffect裡的內容,導致效能問題。

解決方法:

useeffect(() => times`;

}, [count]);

//僅在 count 更改時更新

當我們使用[count]為第二個引數時,它便會去監聽state裡的count如果一致則不執行effect,如果不一致,react會再次呼叫effect.且陣列中如果有多個元素,只要其中乙個改變也會在次呼叫effect。

如果你傳入乙個空陣列(),那麼你將只會執行一次effect(僅在元件掛載和解除安裝時執行)這就告訴react你的effect不依賴於props或state中的任何值。effect內部的props和state就會一直擁有其初始值。

清除effect

在react class中,我們通常會用componentdidmount中設定訂閱,並在componentwillunmount中清除。下面是effect清除

useeffect(() =>;

});

清除可以防止引起內在洩漏,而清除的處理是在react元件解除安裝時執行。

hook使用規則注意

1.只能在函式最外層呼叫hook。不能在迴圈、條件或者子函式中呼叫 。

2.只能在react的函式元件中呼叫hook。

1)官網)

React Hook 的簡單使用

1 什麼是react hook 2 為什麼要使用hook 3 使用usestate建立乙個點贊的小功能import react,from react const likebutton react.fc 點讚 button export default likebutton4 usereffect 的...

react hook 使用注意點

1.useeffect useeffect執行環境 componentdidmount useeffect componentupdate count變數更新時執行 useeffect count componentwillunmount useeffect 2.當在useeffect 使用 變數或...

ReactHook快速上車

react16.8開始內建了10個hook,核心是2個 usestate 有狀態元件寫法 class example extends react.component render times this.setstate click me 無狀態元件寫法 const example props pro...