Hooks学习笔记之useState的使用方式:

1、基础使用方法:

演示地址

(1)、单状态基础使用

import React, { useState } from 'react'

const Test = () => {
    const [count, setCount] = useState(0)
    
    return (
        <div>
            <p>clicked:{ count }</p>
            <button onClick={() => {setCount(count + 1)}}>click</button>
        </div>
    )
}
export default Test

其中count可以理解为原先类表达式中的state.countsetCount可以理解为setState(countVal)
useState(0)当中的(0)count的默认值

(2)、多状态基础使用

import React, { useState } from 'react'

const Test = () => {
    const [age, setAge] = useState(18)
    const [sex, setSex] = useState('男')
    const [work, setWork] = useState('前端')

    return (
        <div>
            <p>我今年: {age}岁</p>
            <p>性别为: {sex}</p>
            <p>工作是: {work}</p>
        </div>
    )
}
export default Test


2、错误使用方式:

(1)、不能在条件语句中使用:

import React, { useState } from 'react'

let showSex = false;
const Test = () => {
    const [age, setAge] = useState(18)
    if(showSex) {
        const [sex, setSex] = useState('男')
        showSex = false;
    }

    return (
        <div>
            <p>我今年: {age}岁</p>
            <p>性别为: {sex}</p>
        </div>
    )
}
export default Test

运行结果为:
1.png