【发布时间】:2021-08-09 02:44:36
【问题描述】:
开发一个 React 应用程序,其主要功能是在用户预先设置的时间间隔内显示句子的每个单词(基本上是快速阅读)。几天前我实现了这一点,但现在我尝试实现一个暂停按钮(暂停循环并获取实际单词)并卡住了。
我决定添加一个暂停按钮,它调用一个将暂停状态设置为真的函数,在我的循环中,如果这个暂停状态为“真”,它就会跳出循环。但问题是,这个循环没有检测到变化,我在第 18 行有一个 console.log,它总是记录为假,尽管我已经点击了暂停按钮并将状态更改为“假”(这正在工作因为我也将它记录在 useEffect 和它的登录 'true')
所以,我的问题是,我该如何解决这个问题?我是不是用错了 react hooks?
代码示例:
const [time, setTime] = React.useState('500')
const [pause, setPause] = React.useState(false)
const go = async function(){
let textarray = text.split(' ') //I split my text
for(let i = 0; i < textarray.length; i++){
console.log(pause) //This keeps logging false although the change in pauseButton function
if(pause){
//Get the actual word => i
break;
}
else{
setValue(textarray[i]) //Show the actual word
await timeout(time) //Wait the time
}
}
}
const pauseButton = function(){
setPause(true)
}
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
【问题讨论】:
标签: javascript reactjs react-hooks