日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React函數式組件Hook中的useEffect函數的詳細解析_React

作者:小馬_xiaoen ? 更新時間: 2022-12-02 編程語言

前言

React函數式編程沒有生命周期,因此需要借助useEffect來實現。

useEffect的作用

  • 發ajax請求獲取數據
  • 設置訂閱/獲取定時器
  • 手動更改真實DOM

useEffect的使用?

1.class組件

在class組件中可以使用生命周期函數,知道組件觸發的過程。

代碼如下(示例):

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.第二個參數為空的情況:在初次渲染執行一次后,會監聽所有數據的更新,數據更新則會觸發useEffect()。(componentDidMount、componentDidUpdate)
    2.第二個參數為[]的情況:回調函數只會在第一次render()后執行。(componentDidMount)
    3.第二個參數為[監聽的元素]:在初次渲染執行一次后,只會監聽相應元素變化才會觸發回調函數。(componentDidMount、componentDidUpdate)
    4.useEffect體中使用了return為一個函數,會在組件卸載前執(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(()=>{
	// 在此可以執行任何帶副作用操作
	return ()=> { // 在組件卸載前執行
		// 在此走一些收尾工作,如清除定時器/取消訂閱等
	}
},[stateValue])// 如果指定的是[],回調函數只會在第一次render()后執行
//如果第二個參數不填,將會監聽所有數據的更新

可以把useEffect Hook 看做如下三個函數的組合

  • componentDidMount()
  • componentDidUpdate()
  • componentWillUnmount()

原文鏈接:https://blog.csdn.net/m0_46165586/article/details/127541468

欄目分類
最近更新