最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

三分鐘搞懂react-hooks及實例代碼

 更新時間:2022年03月10日 11:16:21   作者:六葉草~  
React?Hooks是今年最勁爆的新特性真的毫不夸張。如果你也對react感興趣,或者正在使用react進行項目開發(fā),請抽出點時間閱讀下此文

背景

介紹Hooks之前,首先要說一下React的組件創(chuàng)建方式,一種是類組件,一種是純函數(shù)組件,并且React團隊希望,組件不要變成復(fù)雜的容器,最好只是數(shù)據(jù)流的管道。開發(fā)者根據(jù)需要,組合管道即可。也就是說組件的最佳寫法應(yīng)該是函數(shù),而不是類。
但是我們知道,在以往開發(fā)中類組件和純函數(shù)組件的區(qū)別是很大的,純函數(shù)組件有著類組件不具備的多種特點:

純函數(shù)組件沒有狀態(tài)
純函數(shù)組件沒有生命周期
純函數(shù)組件沒有this

這就注定,我們所推崇的函數(shù)組件,只能做UI展示的功能,涉及到狀態(tài)的管理與切換,我們不得不用類組件或者redux,但我們知道類組件的也是有缺點的,比如,遇到簡單的頁面,代碼會顯得很重,并且每創(chuàng)建一個類組件,都要去繼承一個React實例;至于Redux,更不用多說,很久之前Redux的作者就說過,“能用React解決的問題就不用Redux”。

useState

useState():狀態(tài)鉤子。純函數(shù)組件沒有狀態(tài),useState()用于為函數(shù)組件引入狀態(tài)。

點擊加一效果,分別用類組件和函數(shù)組件實現(xiàn)。可以看出用hooks寫出的代碼更加精簡。
const [count,setCount] = useState(0);//數(shù)組解構(gòu),相當(dāng)于下面三句話
let _useState = useState(0);
let count = _useState[0];
let setState = _useState[1]

類組件

import React,{Component} from "react";
class App1 extends Component{
    constructor(props) {
        super(props);
        this.state={
            count:0
        }
    }
    addCount(){
        this.setState({count:this.state.count+1})
    }
    render() {
        return(
            <div>
                <p>you clicked {this.state.count} times</p>
                <button onClick={this.addCount.bind(this)}>Click me</button>
            </div>
        )
    }

}
export default App1;

函數(shù)組件

使用sueState重寫上面計數(shù)組件。

import React,{useState} from "react";
function App2(){
    const [count,setCount] = useState(0);//數(shù)組解構(gòu)
    return(
        <div>
            <p>You cliked {count} times</p>
            <button onClick={()=>{setCount(count+1)}}>Click me</button>
        </div>
    )
}
export default App2;

多狀態(tài)聲明

使用多條語句聲明不同的狀態(tài)

import React,{useState} from "react";
function App3(){
    const [name,setName] = useState('劉備');//數(shù)組解構(gòu)
    const [age,setAge] = useState(25);
    const [sex,setSex] = useState('男')
    return(
        <div>
            <p>姓名:{name}</p>
            <p>年齡:{age}</p>
            <p>性別:{sex}</p>
        </div>
    )
}
export default App3;

useEffect

useEffect():副作用鉤子??梢杂脕砀玫奶幚砀弊饔?,如異步請求等,Hooks的useEffect()也是為函數(shù)組件提供了處理副作用的鉤子。在類組件中我們會把請求放在componentDidMount里面,在函數(shù)組件中我們可以使用useEffect()。

useEffect相當(dāng)于componentDidMount和componentDidUpdate。
缺點:由于它是異步的因此不能實時處理。

類組件中componentDidMount和componentDidUpdate

import React,{Component} from "react";
class App4 extends Component{
    constructor(props) {
        super(props);
        this.state={
            count:0
        }
    }
    componentDidMount() {
        console.log(`componentDidMount=>you clicked ${this.state.count}`)
    }
    componentDidUpdate() {
        console.log(`componentDidUpdate=>you clicked ${this.state.count}`)
    }

    addCount(){
        this.setState({count:this.state.count+1})
    }
    render() {
        return(
            <div>
                <p>you clicked {this.state.count} times</p>
                <button onClick={this.addCount.bind(this)}>Click me</button>
            </div>
        )
    }

}
export default App4;

useEffect模擬類組件中componentDidMount和componentDidUpdate

import React,{useState,useEffect} from "react";
function App5(){
    const [count,setCount] = useState(0);//數(shù)組解構(gòu)
    useEffect(()=>{
        console.log(`useEffect=>you clicked ${count} times`)
    })
    return(
        <div>
            <p>You cliked {count} times</p>
            <button onClick={()=>{setCount(count+1)}}>Click me</button>
        </div>
    )
}
export default App5;

useEffect實現(xiàn)componmentWillUnment

先寫兩個路由跳轉(zhuǎn)頁面,并配置路由

import React,{useState,useEffect} from "react";
import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom'
function Index(){
    return <h2>Index頁面</h2>
}

function List(){
    return <h2>List頁面</h2>
}

function App5(){
    const [count,setCount] = useState(0);//數(shù)組解構(gòu)
    return(
        <div>
            <div>
                <p>You cliked {count} times</p>
                <button onClick={()=>{setCount(count+1)}}>Click me</button>
            </div>
            <Router>
                    <div>
                        <ul>
                            <li><Link to="/">首頁</Link></li>
                            <li><Link to="/list/">list</Link></li>
                        </ul>
                        <Routes>
                            <Route path="/" exact element={<Index/>}/>
                            <Route path="/list/" element={<List/>}/>
                        </Routes>

                </div>
            </Router>
        </div>
    )
}
export default App5;

使用useEffect表示進入頁面的狀態(tài)。
解綁時使用return,這時發(fā)現(xiàn)我們點擊按鈕時也會發(fā)生改變,這是因為只要組件發(fā)生改變,它就會觸發(fā)解綁。解決方法使用第二個參數(shù)。

import React,{useState,useEffect} from "react";
import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom'
function Index(){
    useEffect(()=>{
        console.log(`useEffect=>Index頁面`)
        return ()=>{
            console.log('跳轉(zhuǎn)頁面')
        }
    })
    return <h2>Index頁面</h2>
}

function List(){
    useEffect(()=>{
        console.log(`useEffect=>List頁面`)
    })
    return <h2>List頁面</h2>
}

function App5(){
    const [count,setCount] = useState(0);//數(shù)組解構(gòu)
    return(
        <div>
            <div>
                <p>You cliked {count} times</p>
                <button onClick={()=>{setCount(count+1)}}>Click me</button>
            </div>
            <Router>

                    <div>
                        <ul>
                            <li><Link to="/">首頁</Link></li>
                            <li><Link to="/list/">list</Link></li>
                        </ul>
                        <Routes>
                            <Route path="/" exact element={<Index/>}/>
                            <Route path="/list/" element={<List/>}/>
                        </Routes>

                </div>
            </Router>
        </div>
    )
}
export default App5;

解綁限制,第二個參數(shù)是一個數(shù)組,如果數(shù)組為空表示頁面被銷毀觸發(fā),如果有變量,表示只有這個變量狀態(tài)變化才會觸發(fā)。

import React,{useState,useEffect} from "react";
import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom'
function Index(){
    useEffect(()=>{
        console.log(`useEffect=>Index頁面`)
        return ()=>{
            console.log('跳轉(zhuǎn)頁面')
        }
    },[])
    return <h2>Index頁面</h2>
}

function List(){
    useEffect(()=>{
        console.log(`useEffect=>List頁面`)
    })
    return <h2>List頁面</h2>
}

function App5(){
    const [count,setCount] = useState(0);//數(shù)組解構(gòu)
    return(
        <div>
            <div>
                <p>You cliked {count} times</p>
                <button onClick={()=>{setCount(count+1)}}>Click me</button>
            </div>
            <Router>

                    <div>
                        <ul>
                            <li><Link to="/">首頁</Link></li>
                            <li><Link to="/list/">list</Link></li>
                        </ul>
                        <Routes>
                            <Route path="/" exact element={<Index/>}/>
                            <Route path="/list/" element={<List/>}/>
                        </Routes>

                </div>
            </Router>
        </div>
    )
}
export default App5;

父子組件傳值useContext

useContext():共享狀態(tài)鉤子。作用就是可以做狀態(tài)的分發(fā),在React16.X以后支持,避免了react逐層通過Props傳遞數(shù)據(jù)。

使用步驟
1、先使用createContext創(chuàng)建上下文
2、然后使用Provider將值給提供出去
3、接收時用useContext接收就可以了

import React,{useState,createContext,useContext} from "react";
const CountContext = createContext();
function Counter(){
    let count = useContext(CountContext);
    return (<h2>{count}</h2>)
}
function App6(){
    const [count,setCount] = useState(0);//數(shù)組解構(gòu)
    return(
        <div>
            <p>You cliked {count} times</p>
            <button onClick={()=>{setCount(count+1)}}>Click me</button>
            <CountContext.Provider value={count}>
                <Counter/>
            </CountContext.Provider>
        </div>
    )
}
export default App6;

useReducer

useReducer():Action鉤子。在使用React的過程中,如遇到狀態(tài)管理,一般會用到Redux,而React本身是不提供狀態(tài)管理的。而useReducer()提供了狀態(tài)管理。首先,關(guān)于redux我們都知道,其原理是通過用戶在頁面中發(fā)起action,從而通過reducer方法來改變state,從而實現(xiàn)頁面和狀態(tài)的通信。而Reducer的形式是(state, action) => newstate。

import React,{useReducer} from "react";
function Reduser(){
    const [count,dispath] = useReducer((state,action)=>{
        switch (action){
            case "add":
                return state+1
            case "sub":
                return state-1
            default:
                return state
        }
    },0)
    return(
        <div>
            <h2>現(xiàn)在的分?jǐn)?shù)是{count}</h2>
            <button onClick={()=>{dispath('add')}}>add</button>
            <button onClick={()=>{dispath('sub')}}>sub</button>
        </div>
    )

}
export default Reduser

到此這篇關(guān)于三分鐘看完react-hooks的文章就介紹到這了,更多相關(guān)react hooks內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • react-native只保留3x圖原理解析

    react-native只保留3x圖原理解析

    這篇文章主要為大家介紹了react-native只保留3x圖原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-01-01
  • React?SSR架構(gòu)Streaming?Render與Selective?Hydration解析

    React?SSR架構(gòu)Streaming?Render與Selective?Hydration解析

    這篇文章主要為大家介紹了React?SSR架構(gòu)Streaming?Render與Selective?Hydration解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03
  • react腳手架構(gòu)建運行時報錯問題及解決

    react腳手架構(gòu)建運行時報錯問題及解決

    這篇文章主要介紹了react腳手架構(gòu)建運行時報錯問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • react中的DOM操作實現(xiàn)

    react中的DOM操作實現(xiàn)

    某些情況下需要在典型數(shù)據(jù)流外強制修改子代。要修改的子代可以是 React 組件實例,也可以是 DOM 元素。這時就要用到refs來操作DOM,本文詳細的介紹一下使用,感興趣的可以了解一下
    2021-06-06
  • React狀態(tài)管理Redux的使用介紹詳解

    React狀態(tài)管理Redux的使用介紹詳解

    redux是redux官方react綁定庫,能夠使react組件從redux store中讀取數(shù)據(jù),并且向store分發(fā)actions以此來更新數(shù)據(jù),這篇文章主要介紹了react-redux的設(shè)置,需要的朋友可以參考下
    2022-09-09
  • react-native-video實現(xiàn)視頻全屏播放的方法

    react-native-video實現(xiàn)視頻全屏播放的方法

    這篇文章主要介紹了react-native-video實現(xiàn)視頻全屏播放的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-03-03
  • ahooks封裝cookie?localStorage?sessionStorage方法

    ahooks封裝cookie?localStorage?sessionStorage方法

    這篇文章主要為大家介紹了ahooks封裝cookie?localStorage?sessionStorage的方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-07-07
  • 關(guān)于react中的常見錯誤及解決

    關(guān)于react中的常見錯誤及解決

    這篇文章主要介紹了關(guān)于react中的常見錯誤及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • React中的useEffect useLayoutEffect到底怎么用

    React中的useEffect useLayoutEffect到底怎么用

    這篇文章主要介紹了React中的useEffect useLayoutEffect具體使用方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧
    2023-02-02
  • webpack打包react項目的實現(xiàn)方法

    webpack打包react項目的實現(xiàn)方法

    這篇文章主要介紹了webpack打包react項目的實現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06

最新評論

德钦县| 祁阳县| 泗水县| 砚山县| 迁安市| 黄浦区| 革吉县| 龙南县| 公安县| 弥勒县| 乳源| 丰镇市| 怀柔区| 聂荣县| 山西省| 麻江县| 乌拉特中旗| 高平市| 沙河市| 阿图什市| 朝阳市| 金平| 伊川县| 曲松县| 株洲市| 九江县| 金坛市| 牙克石市| 乐东| 比如县| 河池市| 新乐市| 万源市| 普兰店市| 化隆| 上虞市| 巴中市| 景东| 建宁县| 鲁甸县| 盖州市|