狀態(state)

用 useState 記住一個值,值一改變,畫面就會重新渲染

重點

  • 會變動的值用 useState 保存:const [count, setCount] = useState(0)
  • 要改變這個值時,一定要用 setCount(下一個值)
  • 值改變後,React 會自動重新渲染畫面,不需要自己去改 DOM

動手試試

import { useState } from "react"

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

  return (
    <div style={{ padding: 16 }}>
      <p>點擊次數:{count}</p>
      <button onClick={() => setCount(count + 1)}>+1</button>
    </div>
  )
}
  1. 把 +1 改成 +10 看看
  2. 加一個 −1 按鈕(提示:setCount(count - 1))
  3. 加一個歸零的重設按鈕(提示:setCount(0))

常見錯誤

用 let count = 0,畫面不會改變
改寫一般變數,React 不會知道需要重新渲染畫面。會變動的值要用 useState 保存。
寫成 onClick={setCount(count + 1)} 會立刻執行
onClick 要傳入的是「之後才執行的函式」。要像 () => setCount(count + 1) 這樣用函式包起來。