在新状态或卸载时反应本地中断循环



我有一个React组件,我想在它被安装时创建一个循环,当它被卸载或当autoGathering状态改变时停止循环。在循环内部,有一个async函数,因此每次迭代都应该等待函数完成,然后再移动到下一个。按下Stop按钮,一切应停止

我的当前和损坏的代码:

const AutoGather = ({autoGathering, stopAutoGather}) => {
useEffect(() => {
for (let i = 0; i < 5; i++) {
if (autoGathering) {
processAutoGather(i, autoGathering).then(() => {
console.log('other ', i)
})
} else {
console.log('stopping')
break
}
}
}, [])

// Some async function here, Database operation and probably a setTimeout
const processAutoGather = async () => {
return new Promise((resolve, reject) => {
if (autoGathering) {
setTimeout(() => {
console.log('resolving')
return resolve(true)
}, 1000)
} else {
console.log('rejecting')
return reject(false)
}
})

}
return (
<Layout style={{flex:1}}>
<Layout style={{flex:1}}>
<Layout style={{flex:1, justifyContent:'center', alignItems:'center'}}>
<Button style={{borderRadius:20, minWidth:125}} onPress={()=> stopAutoGather()} status='danger' size='small'>Stop Auto Gather</Button>
</Layout>
</Layout>
</Layout>
)
}
AutoGather.propTypes = {
autoGathering: PropTypes.bool.isRequired,
materialToGather: PropTypes.string.isRequired,
stopAutoGather: PropTypes.func.isRequired
}
export default AutoGather

您可能希望在启动下一个集合之前等待集合完成。此外,您需要清除useEffect的依赖项:

// Create a promise and save the `resolve` for using outside it
const AutoGather = ({autoGathering, stopAutoGather}) => {
React.useEffect(() => {
let stopTheCount = false;
(async () => {
for (let i = 0; i < 5 && !stopTheCount; i++) {
await processAutoGather(i);
console.log('other ', i);
}
})();
// Stop the count!
return () => { stopTheCount = true };
}, []);
// Some async function here, Database operation and probably a setTimeout
const processAutoGather = async (counter) => {
return autoGathering
? new Promise( (resolve) => {
setTimeout(() => {
if(autoGathering) {
console.log('resolving')
return resolve(true)
}
}, 1000)
})
: Promise.resolve()
}
return (...)
}

最新更新