useState 与状态管理
约 302 字大约 1 分钟
布欧-Lewyon
2026-05-15
useState 基础
import { useState } from 'react'
function Counter() {
const [count, setCount] = useState(0) // useState(初始值)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount(count - 1)}>-1</button>
</div>
)
}函数式更新
// ❌ 直接依赖前值可能会出错(批量更新时)
setCount(count + 1)
setCount(count + 1) // 两次都基于同一个 count 值
// ✅ 函数式更新保证拿到最新值
setCount(prev => prev + 1)
setCount(prev => prev + 1) // 两次累加生效useState 使用对象
function UserForm() {
const [user, setUser] = useState({ name: '', age: 0 })
// ❌ 直接修改对象不触发重渲染
user.name = 'Alice'
// ✅ 创建新对象
setUser({ ...user, name: 'Alice' })
setUser(prev => ({ ...prev, age: 25 }))
}状态提升
function Parent() {
const [count, setCount] = useState(0)
return (
<div>
<p>共享状态: {count}</p>
<ChildA count={count} onIncrement={() => setCount(c => c + 1)} />
<ChildB count={count} />
</div>
)
}小结
useState(初始值)返回[值, 设置函数]。- 用函数式更新
setCount(prev => prev + 1)确保基于最新值。 - state 不可变:必须创建新对象/数组来更新。
- 多个组件共享状态时提升到共同父组件。
上一节:条件渲染与列表 下一节:useEffect 与副作用
