如何在 useEffect 中 return false 或 true 并将其传递给另一个 useEffect 方法
How to return a false or true inside the useEffect and pass it to another useEffect method
我想获取最新的useEffect的值,是true还是false,并将其传递到第一个useEffect的花括号中,这样当它升级或下降时,它就会停止递减倒计时。
const curLevel = 2;
const newTimer = curLevel * 15;
const timeRef = useRef(null);
const level = useRef(null);
const [ seconds, setSeconds ] = useState(newTimer);
// countdown
useEffect(() => {
const timer = setInterval(() => setSeconds(seconds => seconds - 1), 1000);
timeRef.current = timer;
return () => clearInterval(timer);
}, []);
useEffect(() => {
if(seconds === 0 || {pass returned value here} ) clearInterval(timeRef.current);
}, [seconds]);
// level comparison
useEffect(() => {
const storedLevel = curLevel;
level.current = storedLevel;
return () => storedLevel
}, []);
useEffect(() => {
console.log(level.current, curLevel) // outputs (2,3)
if(level.current !== curLevel) {}
// I want to get the value (which is true or false and pass it into the curly bracket of the first useEffect, so it will stop decrementing the countdown when it goes level up or down.
},[]);
您需要将该布尔值 属性 添加到状态,然后在您的第一个 useEffect
:
中跟踪它
const [isCurrentlevel, setIsCurrentLevel] = useState(false);
//...
useEffect(() => {
if (isCurrentLevel) {
const timer = setInterval(() => setSeconds(seconds => seconds - 1), 1000);
timeRef.current = timer;
return () => clearInterval(timer);
}
}, [isCurrentlevel]);
useEffect(() => {
console.log(level.current, curLevel) // outputs (2,3)
setIsCurrentLevel(level.current !== curLevel);
},[level.current, curLevel]);
我想获取最新的useEffect的值,是true还是false,并将其传递到第一个useEffect的花括号中,这样当它升级或下降时,它就会停止递减倒计时。
const curLevel = 2;
const newTimer = curLevel * 15;
const timeRef = useRef(null);
const level = useRef(null);
const [ seconds, setSeconds ] = useState(newTimer);
// countdown
useEffect(() => {
const timer = setInterval(() => setSeconds(seconds => seconds - 1), 1000);
timeRef.current = timer;
return () => clearInterval(timer);
}, []);
useEffect(() => {
if(seconds === 0 || {pass returned value here} ) clearInterval(timeRef.current);
}, [seconds]);
// level comparison
useEffect(() => {
const storedLevel = curLevel;
level.current = storedLevel;
return () => storedLevel
}, []);
useEffect(() => {
console.log(level.current, curLevel) // outputs (2,3)
if(level.current !== curLevel) {}
// I want to get the value (which is true or false and pass it into the curly bracket of the first useEffect, so it will stop decrementing the countdown when it goes level up or down.
},[]);
您需要将该布尔值 属性 添加到状态,然后在您的第一个 useEffect
:
const [isCurrentlevel, setIsCurrentLevel] = useState(false);
//...
useEffect(() => {
if (isCurrentLevel) {
const timer = setInterval(() => setSeconds(seconds => seconds - 1), 1000);
timeRef.current = timer;
return () => clearInterval(timer);
}
}, [isCurrentlevel]);
useEffect(() => {
console.log(level.current, curLevel) // outputs (2,3)
setIsCurrentLevel(level.current !== curLevel);
},[level.current, curLevel]);