一、react-hooks概念
React中一切皆為組件,React中組件分為類組件和函數組件,在React中如果需要記錄一個組 件狀態得時候,那么這個組件必須是類組件,那么能否讓函數組件擁有類組件得功能?這時候 我們就需要使用hook
Hooks讓我們函數組件擁有了類似組件得特性,Hook是React16.8中新增得功能,他們允許 您在不編寫類的情況下使用狀態和其他React功能
二、為什么React中需要類組件
1、需要記錄當前組件的狀態 2、需要使用組件的一些生命周期
三、類組件與Hooks對比
import React, { Component,Fragment} from "react"; export default class App extends Component{ constructor(){ super(); this.state = { n:0 } this.handleClick = this.handleClick.bind(this) } render(){ let {n} = this.state return( <div> <h3>{n}</h3> <button onClick={this.handleClick}>修改</button> </div> ) } handleClick(){ this.setState({ n:this.state.n+1 }) } } 函數組件 import React, { Component,Fragment,useState} from "react"; export default ()=>{ let [n,setCount] = useState(0); const handleClick = ()=>{ n+=1; setCount(n) } return ( <div> <h3>{n}</h3> <button onClick={handleClick}>點擊</button> </div> ) } useState:創建一個狀態,這個狀態為0 n:代表當前狀態值也是0 setCount:更新狀態的函數
四、Hooks常用的方法
useState、useEffect、useContext
useState:函數 存儲的當前組件的一些狀態 參數:所需要的狀態值 返回值:數組 1.當前狀態的Key值 2.修改當前狀態的函數
五、useEffect基本使用
模擬組件狀態的一些生命周期 比如:componentDidMount、componentDidUpdate、componentWillUnmount
useEffect中有兩個參數 第一個參數是一個函數, 第二個參數是一個依賴的數據。 第二個參數用來決定是否執行里面的操作,可以避免一些不必要的性能損失, 只要第二個參數中的成員的值沒有改變,就會跳過此次執行。 如果傳入一個空數組[],那么該effect只會在組件mount和unmount時期執行
useEffect模擬componentDidMount && componentDidUpdate
import React, { Component,Fragment,useState,useEffect} from "react"; export default ()=>{ let [n,setCount] = useState(0); const handleClick = ()=>{ n+=1; setCount(n) } useEffect(() => { console.log(111) }) return ( <div> <h3>{n}</h3> <button onClick={handleClick}>點擊</button> </div> ) }
只在componentDidMount中執行
import React, { Component,Fragment,useState,useEffect} from "react"; export default ()=>{ let [n,setCount] = useState(0); const handleClick = ()=>{ n+=1; setCount(n) } useEffect(() => { console.log(111) },[]) return ( <div> <h3>{n}</h3> <button onClick={handleClick}>點擊</button> </div> ) }
useEffect模擬componentWillUnMount
useEffect中還可以通過讓函數返回一個函數來進行一些清理操作(比如事件的移除)
useEffect(() => { console.log(111) return()=>{ console.log("卸載") } },[])