欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

背景

介紹Hooks之前,首先要說一下React的組件創(chuàng)建方式,一種是類組件,一種是純函數(shù)組件,并且React團隊希望,組件不要變成復雜的容器,最好只是數(shù)據(jù)流的管道。開發(fā)者根據(jù)需要,組合管道即可。也就是說組件的最佳寫法應該是函數(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)??梢钥闯鲇胔ooks寫出的代碼更加精簡。
const [count,setCount] = useState(0);//數(shù)組解構,相當于下面三句話
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ù)組解構
    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ù)組解構
    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相當于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ù)組解構
    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

先寫兩個路由跳轉頁面,并配置路由

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ù)組解構
    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('跳轉頁面')
        }
    })
    return <h2>Index頁面</h2>
}

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

function App5(){
    const [count,setCount] = useState(0);//數(shù)組解構
    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('跳轉頁面')
        }
    },[])
    return <h2>Index頁面</h2>
}

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

function App5(){
    const [count,setCount] = useState(0);//數(shù)組解構
    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ù)組解構
    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)管理。首先,關于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)在的分數(shù)是{count}</h2>
            <button onClick={()=>{dispath('add')}}>add</button>
            <button onClick={()=>{dispath('sub')}}>sub</button>
        </div>
    )

}
export default Reduser

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

相關文章

  • react如何同步獲取useState的最新狀態(tài)值

    react如何同步獲取useState的最新狀態(tài)值

    這篇文章主要介紹了react如何同步獲取useState的最新狀態(tài)值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • 用react-redux實現(xiàn)react組件之間數(shù)據(jù)共享的方法

    用react-redux實現(xiàn)react組件之間數(shù)據(jù)共享的方法

    這篇文章主要介紹了用react-redux實現(xiàn)react組件之間數(shù)據(jù)共享的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06
  • React實現(xiàn)下拉框的key,value的值同時傳送

    React實現(xiàn)下拉框的key,value的值同時傳送

    這篇文章主要介紹了React實現(xiàn)下拉框的key,value的值同時傳送方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • 關于React中setState同步或異步問題的理解

    關于React中setState同步或異步問題的理解

    相信很多小伙伴們都一直在疑惑,setState 到底是同步還是異步。本文就詳細的介紹一下React中setState同步或異步問題,感興趣的可以了解一下
    2021-11-11
  • React?Hooks鉤子中API的使用示例分析

    React?Hooks鉤子中API的使用示例分析

    在react類組件(class)寫法中,有setState和生命周期對狀態(tài)進行管理,但是在函數(shù)組件中不存在這些,故引入hooks(版本:>=16.8),使開發(fā)者在非class的情況下使用更多react特性
    2022-08-08
  • jsoneditor二次封裝實時預覽json編輯器組件react版

    jsoneditor二次封裝實時預覽json編輯器組件react版

    這篇文章主要為大家介紹了jsoneditor二次封裝實時預覽json編輯器組件react版示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-10-10
  • 使用React實現(xiàn)一個簡單的待辦任務列表

    使用React實現(xiàn)一個簡單的待辦任務列表

    這篇文章主要給大家介紹了使用React和Ant Design庫構建的待辦任務列表應用,它包含了可編輯的表格,用戶可以添加、編輯和完成任務,以及保存任務列表數(shù)據(jù)到本地存儲,文中有相關的代碼示例,需要的朋友可以參考下
    2023-08-08
  • 記一個React.memo引起的bug

    記一個React.memo引起的bug

    memo可以自己決定是否更新,但它是一個函數(shù)組件而非一個類,本文主要介紹了React.memo引起的bug,具有一定的參考價值,感興趣的可以了解一下
    2022-03-03
  • React Native中導航組件react-navigation跨tab路由處理詳解

    React Native中導航組件react-navigation跨tab路由處理詳解

    這篇文章主要給大家介紹了關于React Native中導航組件react-navigation跨tab路由處理的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。
    2017-10-10
  • hooks寫React組件的5個注意細節(jié)詳解

    hooks寫React組件的5個注意細節(jié)詳解

    這篇文章主要為大家介紹了hooks寫React組件的5個需要注意的細節(jié)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03

最新評論