gpt4 book ai didi

javascript - 如何打破循环 onClick ReactJS

转载 作者:行者123 更新时间:2023-12-05 03:46:05 27 4
gpt4 key购买 nike

我有一个使用 async await() 制作动画的函数。 我想播放/暂停动画 onClick。我使用 useState 来更新变量,但该函数的行为并不如我所愿。当 const print () 正在运行时,当我单击按钮时,文本会更新,但函数不会中断。在日志中,“播放”被打印了 100 次。我猜是 useStateasync 引起的。我该如何解决这个问题?

const Test= props => {

const [ButtonText, SetButtonText] = useState("Play");
const ToggleButtonText = () => {
if(ButtonText == "Play")
SetButtonText("Pause")

if(ButtonText == "Pause")
SetButtonText("Play")
}

const delay = ms => new Promise(res => setTimeout(res, ms));

const print= () => {
for(var i = 0; i < 100; i++)
{
///
work
await delay(1000);
work
///
console.log(ButtonText);

if(ButtonText == "Pause")
break ;

}
};
return (
<div>
<div>
///work component///
</div>
<button onClick = {() => ToggleButtonText()}> {ButtonText}</button>
</div>
)
}

最佳答案

ButtonText 被声明为 const - 它不能在功能组件的给定调用中更改其值。

在没有更多信息的情况下,我将使用 ref 和状态,以便循环可以查看 ref 是否已更改:

const buttonTextRef = useRef();
// Update the ref to ButtonText every time ButtonText changes:
useEffect(() => {
buttonTextRef.current = ButtonText;
}, [ButtonText]);
if (buttonTextRef.current === 'Pause') {
break;
}

另一种方法是将正在迭代的索引放入状态,而不是循环 100 次,而是重新渲染 100 次,例如,类似于:

const [printI, setPrintI] = useState(0);
if (printI) {
// Then we're in the middle of iterating
// work
if (printI < 100) {
setTimeout(() => {
setPrintI(printI + 1);
}, 1000);
} else {
setPrintI(0);
}
};

要停止它,请调用 setPrintI(0)

关于javascript - 如何打破循环 onClick ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65473043/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com