1 javascript setinterval reactjs react-functional-component
在我的代码中,我遇到一些间隔问题。我有这样的情况
import { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
function handleClick() {
const timer = setInterval(() => {
if (count >= 10) {
clearInterval(timer);
} else {
setCount((prevCount) => prevCount + 1);
}
}, 1000);
}
return (
<>
<button onClick={handleClick}>start</button>
<p>{count}</p>
</>
);
}
export default App;
Run Code Online (Sandbox Code Playgroud)
我想做的是当用户单击按钮时启动一个间隔,并在计数器达到 10 时停止它,但它永远不会停止,调试器说内部setInterval计数始终为 0。有人知道问题是什么吗?我还发现,如果我class像这样将组件重写为组件
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
handleClick() {
let myInterval = setInterval(() => {
if (this.state.count >= 10) {
clearInterval(myInterval);
} else {
this.setState((prevState) => ({
count: prevState.count + 1,
}));
}
}, 1000);
}
render() {
return (
<>
<button onClick={this.handleClick.bind(this)}>start</button>
<p>{this.state.count}</p>
</>
);
}
}
Run Code Online (Sandbox Code Playgroud)
它工作得很好。
我不知道发生了什么,我花了几乎一整天的时间试图弄清楚。
那么有人知道为什么class组件可以工作以及为什么functional组件不能工作吗?
提前致谢
您在回调函数中看到了陈旧的内容,因为它捕获了您启动计时器时的值countsetInterval。
您可以使用“ref boxing”模式来获得对状态原子最新值的可读引用:
import {useState, useRef} from 'react';
function App() {
const [count, setCount] = useState(0);
const countRef = useRef(null);
countRef.current = count; // Update the boxed value on render
function handleClick() {
const timer = setInterval(() => {
if (countRef.current >= 10) { // Read the boxed value
clearInterval(timer);
} else {
setCount((prevCount) => prevCount + 1);
}
}, 1000);
}
return (
<>
<button onClick={handleClick}>start</button>
<p>{count}</p>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
请注意,您当前没有正确清理卸载时的计时器,导致 React 在您卸载应用程序时发出警告。这同样适用于你的类组件。
| 归档时间: |
|
| 查看次数: |
2276 次 |
| 最近记录: |