React Hooks与easy-peasy学习笔记

React Hooks

1. useState

useState这个函数接收的参数是state的初始值,它返回一个数组

该数组的第一个值表示当前状态值

第二个值表示更新状态值的函数

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

等价于

使用ES6的数组解构语法糖

const [count, setCount] = useState(0)

{count}显示状态值

setCount更新状态值,有两种写法

一种是直接传入值setCount(count+1)

另外一种是传入箭头函数

setCount((c) => c + 1)

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

    return <div>
        <div>count = {count}</div>
        <p style={{ marginTop: '20px' }}>写法一,直接传入数值</p>
        <button onClick={() => setCount(count + 1)}>add</button>
        <button onClick={() => setCount(count - 1)}>minus</button>
        <p style={{ marginTop: '20px' }}>写法二,参数为箭头函数</p>
        <button onClick={() => setCount((c) => c + 1)}>add</button>
        <button onClick={() => setCount((c) => c - 1)}>minus</button>
    </div>
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容