React Hooks與easy-peasy學(xué)習(xí)筆記

React Hooks

1. useState

useState這個(gè)函數(shù)接收的參數(shù)是state的初始值,它返回一個(gè)數(shù)組

該數(shù)組的第一個(gè)值表示當(dāng)前狀態(tài)值

第二個(gè)值表示更新狀態(tài)值的函數(shù)

let countArray = useState(0)
let count = countArray[0]
let setCount = countArray[1]

等價(jià)于

使用ES6的數(shù)組解構(gòu)語法糖

const [count, setCount] = useState(0)

{count}顯示狀態(tài)值

setCount更新狀態(tài)值,有兩種寫法

一種是直接傳入值setCount(count+1)

另外一種是傳入箭頭函數(shù)

setCount((c) => c + 1)

export default function UseStatePage() {
    const [count, setCount] = useState(0)

    return <div>
        <div>count = {count}</div>
        <p style={{ marginTop: '20px' }}>寫法一,直接傳入數(shù)值</p>
        <button onClick={() => setCount(count + 1)}>add</button>
        <button onClick={() => setCount(count - 1)}>minus</button>
        <p style={{ marginTop: '20px' }}>寫法二,參數(shù)為箭頭函數(shù)</p>
        <button onClick={() => setCount((c) => c + 1)}>add</button>
        <button onClick={() => setCount((c) => c - 1)}>minus</button>
    </div>
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容