Skip to content

useState

介绍

useState 是一个 hooks 函数,它允许我们向组件添加一个状态变量,从而控制影响组件的渲染结果。

提示

可以类比于 vue2 中的 data,或者 vue3 中的 ref、reactive。

示例

tsx
import { useState } from 'react'

function State() {
  const [count, setCount] = useState(0)
  const handleClick = () => {
    setCount(count + 1)
  }

  const [obj, setObj] = useState({
    name: '张三',
    age: 18,
  })
  const handleClick2 = () => {
    setObj({
      ...obj,
      name: '李四',
    })
  }

  const [arr, setArr] = useState([1, 2, 3])
  const handleClick3 = () => {
    setArr([4, 5, 6])
  }

  return (
    <>
      {/* 基本状态 */}
      <h2>{count}</h2>
      <button type="button" onClick={handleClick}>
        count++
      </button>

      <hr />
      {/* 对象状态 */}
      <h2>{JSON.stringify(obj)}</h2>
      <button type="button" onClick={handleClick2}>
        更改 obj
      </button>

      <hr />
      {/* 数组状态 */}
      <h2>{JSON.stringify(arr)}</h2>
      <button type="button" onClick={handleClick3}>
        添加 arr
      </button>
    </>
  )
}

export default State

计算属性

jsx
import { useState } from 'react'

function App() {
  const [count] = useState(10)
  const doubleCount = count * 2

  return <div>{doubleCount}</div>
}

export default App

基于 MIT 许可发布