在函数组件中,如果我们在回调函数中使用了 state 的值,那么闭包就会产生。闭包在函数创建时产生,他会缓存创建时的 state 的值。
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0)
function handle() {
setCount(count + 1)
// 当 setTimeout 执行时,
// 回调函数的 count 值不是 1,而是 0
setTimeout(() => {
setCount(count + 2)
}, 0)
}
return (
<div>
<div>{count}</div>
<button onClick={handle}>递增</button>
</div>
)
}
如果我们要在 setTimeout 回调函数中,正确的拿到当前 state 的值,我们可以使用如下的写法来达到目的
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0)
function handle() {
setCount(count + 1)
setTimeout(() => {
- setCount(count + 2)
+ setCount(count => count + 2) // 异步写法
}, 0)
}
return (
<div>
<div>{count}</div>
<button onClick={handle}>递增</button>
</div>
)
}