React函數式組件Hook中的useEffect函數的詳細解析
更新時間:2022年10月27日 14:11:53 作者:小馬_xiaoen
useEffect是react v16.8新引入的特性。我們可以把useEffect hook看作是componentDidMount、componentDidUpdate、componentWillUnmounrt三個函數的組合
前言
React函數式編程沒有生命周期,因此需要借助useEffect來實現(xiàn)。
useEffect的作用
- 發(fā)ajax請求獲取數據
- 設置訂閱/獲取定時器
- 手動更改真實DOM
useEffect的使用?
1.class組件
在class組件中可以使用生命周期函數,知道組件觸發(fā)的過程。
代碼如下(示例):
import React, { Component } from 'react' export default class App extends Component { constructor(p){ super(p) this.state = {num: 0} } render() { return ( <div> <h2>{this.state.num}</h2> <button onClick={this.addNum.bind(this)}>累加</button> </div> ) } componentDidMount(){ console.log('Mount') } componentDidUpdate(){ console.log('Update') } componentWillUnmount(){ consoloe.log('Unmount') } addNum(){ this.setState({ num: this.state.num+1 }) } }
生命周期(圖)
2.函數式組件
函數式組件中沒有自己的生命周期,需要使用useEffect模擬生命周期。
代碼如下(示例):
import React, { useState, useEffect } from 'react' function App1(){ const [num, setNum] = useState(0); const [num1, setNum1] = useState(1) /* 1.第二個參數為空的情況:在初次渲染執(zhí)行一次后,會監(jiān)聽所有數據的更新,數據更新則會觸發(fā)useEffect()。(componentDidMount、componentDidUpdate) 2.第二個參數為[]的情況:回調函數只會在第一次render()后執(zhí)行。(componentDidMount) 3.第二個參數為[監(jiān)聽的元素]:在初次渲染執(zhí)行一次后,只會監(jiān)聽相應元素變化才會觸發(fā)回調函數。(componentDidMount、componentDidUpdate) 4.useEffect體中使用了return為一個函數,會在組件卸載前執(zhí)(componentWillUnmount) */ useEffect(()=>{ console.log('useEffect') }, [num]) return ( <div> <h1>{num}</h1> <button onClick={()=>setNum(num+1)}>累加</button> <h1>{num1}</h1> <button onClick={()=>setNum1(num1+1)}>累加</button> </div> ) } export default App1;
總結
語法和說明
useEffect(()=>{ // 在此可以執(zhí)行任何帶副作用操作 return ()=> { // 在組件卸載前執(zhí)行 // 在此走一些收尾工作,如清除定時器/取消訂閱等 } },[stateValue])// 如果指定的是[],回調函數只會在第一次render()后執(zhí)行 //如果第二個參數不填,將會監(jiān)聽所有數據的更新
可以把useEffect Hook 看做如下三個函數的組合
- componentDidMount()
- componentDidUpdate()
- componentWillUnmount()
到此這篇關于React函數式組件Hook中的useEffect函數的詳細解析的文章就介紹到這了,更多相關React useEffect內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
React前端渲染優(yōu)化--父組件導致子組件重復渲染的問題
本篇文章是針對父組件導致子組件重復渲染的優(yōu)化方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08