英文:
How to clearInterval of the function that has started and running with setInterval?
问题
如何在设置worker
值为"0"时停止loadFriendList
的加载?
const [worker, setWorker] = useState('1');
function start() {
setInterval(loadFriendList, 5000);
}
useEffect(start, []);
function n() {
setWorker("0");
Alert.alert('check', worker);
}
英文:
how to stop the loadFriendList when setWorker Value is"0"?
const [worker, setWorker] = useState('1');
function start() {
setInterval(loadFriendList,5000);
}
useEffect(start, []);
function n() {
setWorker("0");
Alert.alert('check', worker);
}
答案1
得分: 2
不要将字符串用作数字,这是不必要的麻烦。
使用useRef
钩子来存储intervalID。
此useEffect
钩子在worker更改时触发。
!在[]
中看到我们添加了worker变量。这被称为依赖数组。基本上,你在告诉useEffect
观察这些变量,并在任何变化时触发。
useEffect(() => {
if (worker === 0) intID.current && clearInterval(intId.current)
}, [worker])
useRef
钩子保持页面加载时设置的Interval,以唯一标识并在将来运行clearInterval()
等方法。
最终应该如下所示
const [worker, setWorker] = useState(1);
const intId = useRef(null)
useEffect(() =>{
intId.current = setInterval(loadFriendList, 5000);
return () => clearInterval(intId.current)
}, []);
useEffect(() => {
if (worker === 0) intId.current && clearInterval(intId.current)
}, [worker])
英文:
>Don't use strings as number it's an unnecessary hassle .
> use useRef
hook to store intervalID .
This useEffect
hook fires whenever worker is change.
>! see inside the []
we've added worker variable. It's called dependancy array. Basically you're saying to useEffect look on these variables and fire if anything changes
useEffect(() => {
if(worker == 0) intID.current && clearInterval(intId.current)
},[worker])
The useRef
hook is holding on to the Interval you set up when page loading, to uniquely identify and run methods like clearInterval()
in future
Finally It Should Look Like
const [worker, setWorker] = useState(1);
const intId = useRef(null)
useEffect(() =>{
intId.current = setInterval(loadFriendList,5000);
return () => clearInterval(intId.current)
}, []);
useEffect(() => {
if(worker == 0) intId.current && clearInterval(intId.current)
},[worker])
答案2
得分: 0
const [worker, setWorker] = useState('1');
const [intervalId, setIntervalId] = useState(null);
function start() {
setIntervalId(setInterval(loadFriendList, 5000));
}
useEffect(start, []);
function n() {
setWorker("0");
clearInterval(intervalId);
Alert.alert('check', worker);
}
英文:
const [worker, setWorker] = useState('1');
const [intervalId, setIntervalId] = useState(null);
function start() {
setIntervalId(setInterval(loadFriendList, 5000));
}
useEffect(start, []);
function n() {
setWorker("0");
clearInterval(intervalId);
Alert.alert('check', worker);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论