React useState — 状态管理
用 useState Hook 管理组件自身的状态 · 难度:进阶 · +25XP
useState — 函数组件的"记忆"
useState 是最常用的 Hook,让函数组件能够记住数据,数据变了自动重渲染。
基本用法
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
// 变量 设置函数 初始值
return (
<div>
<p>点击了 {count} 次</p>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount(0)}>重置</button>
</div>
);
}
状态更新规则
| 规则 | 说明 |
|---|---|
| 异步更新 | setState 不会立即改变值 |
| 不可变 | 对象/数组要创建新引用:setUser({...user, name:"new"}) |
| 函数式更新 | setCount(c => c + 1) 基于前值 |
多个 state vs 一个对象
// ✅ 推荐:多个 useState(简单清晰)
const [name, setName] = useState("");
const [age, setAge] = useState(0);
// 也可以用对象(但更新要小心展开)
const [form, setForm] = useState({ name: "", age: 0 });
setForm({ ...form, name: "张三" }); // 必须展开!