我正在构建一个简单的 React 应用程序,在单击按钮时更新状态。但是,当状态发生变化时,我的组件不会按预期重新渲染。这是我的代码:
import React, { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>Click me</button>
</div>
);
}
export default App;
I expected the paragraph to update and display the new count each time I clicked the button, but it remains at 0. I've verified that the handleClick function is being called and setCount is executing.
您需要将其用作回调函数。