useState
使用
const [state, setState] = useState(initialState)initalState
使用一个函数来获得初始值
function getInitValue() {
return 0
}
function Counter() {
// ❌ 错误做法,会导致每次 re-render 时重新调用 getInitValue()
const [count, setCount] = useState(getInitValue())
...
}根据当前 state 更新 newState
通过 updater 函数来更新


setState() 的坑
setState() 参数
setState() 返回
更新对象或数组
更新对象
更新数组
❌
✅
其他应用
通过 key 来重置 state
保存上一次更新的信息
使用 useState() 来保存一个函数
Immutable
为什么 state 要设计成 immutable 的?
Last updated