3.6 Hook
UseEffect
沒有使用Hook的寫法:
以useEffect
方法寫,出乎意料簡潔:
原本應在
componentDidMount
的是 setCounter(counter=>10)原本應在
componentWillUnmount
的是 setCounter(counter=>0)
componentDidUpdate
呢? 有趣的是,上面並沒有對應 componentDidUpdate
的地方,因為在useEffect
第二個參數,有一個empty array。第二個參數是此effect的dependency,React會儲起每次這個array的數值,如果在下一次update的時候發現這個array改變了,就代表了 這個effect需要重新運行。由於一個empty array永遠都是一樣,所以我們這個useEffect只會運行一次!如果沒有了第二個參數,那就變成了 componentDidUpdate
+componentDidMount
了。
Last updated