首先,我无法找出这段代码中的问题。但这个问题可能在这里有一席之地。
据我所知,问题可能是单击按钮后计数器值没有更新。尽管在 2.5 秒的延迟期间我单击并增加了计数器的值,但警报会在单击按钮时显示该值。
我是对的吗?如果是的话,这里应该修复或添加什么?
import React, { useState } from 'react'
function Root() {
const [count, setCount] = useState(0)
function handleAlertClick() {
setTimeout(() => {
alert(`You clicked ${count} times`)
}, 2500)
}
return (
<Container>
<Column>
<h4>Closures</h4>
<p>You clicked {count} times</p>
<button type="button" onClick={() => setCount(counter => counter + 1)}>
Click me
</button>
<button type="button" onClick={handleAlertClick}>
Show alert
</button>
</Column>
</Container>
)
}
export default Root
Run Code Online (Sandbox Code Playgroud)