useEffect中return函數(shù)的作用和執(zhí)行時機解讀
更新時間:2024年01月04日 09:01:33 作者:淘淘是只狗
這篇文章主要介紹了useEffect中return函數(shù)的作用和執(zhí)行時機,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
useEffect中return函數(shù)作用和執(zhí)行時機
官網(wǎng)的代碼
import React, { useState, useEffect } from 'react'; function FriendStatus(props) { const [isOnline, setIsOnline] = useState(null); useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); // Specify how to clean up after this effect: return function cleanup() { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); if (isOnline === null) { return 'Loading...'; } return isOnline ? 'Online' : 'Offline'; }
這是effect可選的清除機制
每個 effect 都可以返回一個清除函數(shù)。
React會在組件卸載的時候執(zhí)行清除操作
effect 在每次渲染的時候都會執(zhí)行。
React 會在執(zhí)行當(dāng)前 effect 之前對上一個 effect 進行清除。
import { useEffect, useState } from 'react'; const Example = () => { const [count, setCount] = useState(0); useEffect(() => { console.log("哈哈哈,useEffect 又執(zhí)行了"); return () => { console.log("看到我就知道執(zhí)行了清除機制(~ ̄▽ ̄)~"); }; }, [count]); return ( <div> <p>那啥,你點了我 {count} 次 ????????</p> {console.log("這是 dom 節(jié)點渲染了,小樣╭(╯^╰)╮")} <button onClick={() => { setCount(count + 1); }} > 你覺得你點擊我之后會發(fā)生什么?????? </button> </div> ); }; function App() { return ( <div className="App"> <Example /> </div> ); } export default App;
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解create-react-app 自定義 eslint 配置
這篇文章主要介紹了詳解create-react-app 自定義 eslint 配置,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06修復(fù)Next.js中window?is?not?defined方法詳解
這篇文章主要為大家介紹了修復(fù)Next.js中window?is?not?defined方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12