每当特定状态发生变化时,是否可以调用我定义的函数?
例如:
function Component(props) {
const [timerOn, setTimerOn] = useState(false);
function startTimer() {
setTimerOn(true);
setTimeout(1000, () => setTimerOn(false))
}
startTimer();
}
每当调用setTimerOn(false)时,我都需要调用startTimer。如何在不渲染屏幕的情况下每次调用startTimer来做到这一点?
Since you are already hooks. The useEffect hooks will come to your rescue in this scenerio. More about it here
useEffect is perfect here since you're already using React hooks. As stated in the official documentation -
所以就你而言
You can use the hook useEffect, this hook lets you execute code when any of the values inside the dependency array changes. You can use it like this
编辑以丰富答案:
您可以执行以下操作:
In any case, I can't think of an scenario that you need to restart a timer when you can use setInterval. That function executes a function every 'n' seconds. And it's used like:
问候