react hook
什么是Effect Hooks?
替代原來的生命周期函數(shù)
hooks可以反復(fù)多次使用,給每一個(gè)副作用一個(gè)單獨(dú)的useEffect鉤子惧盹。這
這樣,副作用不會(huì)堆在生命周期鉤子里,代碼更加清晰。
useEffect怎么用
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
注意:
每次渲染都會(huì)調(diào)用一遍傳給useEffect的函數(shù)
useEffect中定義的副作用函數(shù)的執(zhí)行不會(huì)阻礙瀏覽器更新視圖榄审,也就是說這些函數(shù)是異步執(zhí)行的,而之前的componentDidMount或componentDidUpdate中的代碼則是同步執(zhí)行的杆麸。
useEffect怎么解綁
當(dāng)我們?cè)赾omponentDidMount里添加了一個(gè)注冊(cè)搁进,我們得馬上在componentWillUnmount中,也就是組件被注銷之前清除掉我們添加的注冊(cè)昔头,否則內(nèi)存泄漏的問題就出現(xiàn)了饼问。
怎么清除呢?讓我們傳給useEffect的副作用函數(shù)返回一個(gè)新的函數(shù)即可揭斧。這個(gè)新的函數(shù)將會(huì)在組件下一次重新渲染之后執(zhí)行莱革。這種模式在一些pubsub模式的實(shí)現(xiàn)中很常見《锟看下面的例子:
import { useState, useEffect } from 'react';
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
useEffect(() => {
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// 一定注意下這個(gè)順序:告訴react在下次重新渲染組件之后盅视,同時(shí)是下次調(diào)用ChatAPI.subscribeToFriendStatus之前執(zhí)行cleanup
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
這里有一個(gè)點(diǎn)需要重視!這種解綁的模式跟componentWillUnmount不一樣萧吠。componentWillUnmount只會(huì)在組件被銷毀前執(zhí)行一次而已左冬,而useEffect里的函數(shù)桐筏,每次組件渲染后都會(huì)執(zhí)行一遍纸型,包括副作用函數(shù)返回的這個(gè)清理函數(shù)也會(huì)重新執(zhí)行一遍。