经典示例,并不清楚为什么具有直接值的 setter 不起作用 setCount(count+1) 应用程序仅包含 1 并停止计数,但是每秒都会调用间隔函数,如果我们放置日志,我们就可以看到它。
const { useState, useEffect } = React;
const Counter = () => {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => setCount(count+1), 1000);
// this set count works
// const id = setInterval(() => setCount(c => c + 1), 1000);
return () => clearInterval(id);
}, []);
return (<div>{count}<button onClick={()=>setCount(10)}>Give10</button></div>);
};
ReactDOM
.createRoot(root)
.render(<Counter/ >);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>