用函数式写法更新state
import { useState } from "react"
const Counter = ()=> {
const [count, setCount] = useState(0)
console.log(111);
const handleCount = ()=> {
// react 状态更新是异步的,这么写不保证拿到最新值
// 当前页面这么写测试没问题,可能是按钮点击的速度不够快
// setCount(count + 1)
// 函数式写法可以保证拿到最新值
setCount(prevCount => prevCount + 1) // 推荐这么写
}
return (
<>
<div>{count}</div>
<button onClick={handleCount}>increase</button>
</>
)
}
export default Counter