[英]React - Checking for a change of state every few seconds
In React js, I want to call a function when a state is set to pending.在 React js 中,我想在状态设置为挂起时调用一个函数。
This state is only changed when the API call is completed which can take a number of seconds.此状态仅在 API 调用完成时才会更改,这可能需要几秒钟的时间。
The flow is:流程是:
How would you recommend 'looping' to check for this change of state every few seconds?您如何建议“循环”每隔几秒钟检查一次状态变化?
I have tried with componentDidUpdate() but haven't had much luck.我尝试过 componentDidUpdate() 但运气不佳。
Cheers干杯
Edit:编辑:
To clarify - I'm waiting on an API call that takes a couple of seconds meaning I'd need to periodically check back.澄清一下 - 我正在等待一个需要几秒钟的 API 调用,这意味着我需要定期检查。
How would you recommend 'looping' to check for this change of state every few seconds?您如何建议“循环”每隔几秒钟检查一次状态变化?
I wouldn't.我不会。 I'd handle the completion of the API call.我会处理 API 调用的完成。 If it's asynchronous (as you imply), it will provide a way to be notified when it completes — it'll accept a callback, or return a promise, that sort of thing.如果它是异步的(如您所暗示的那样),它将提供一种在完成时收到通知的方式——它将接受回调或返回承诺,诸如此类。 Use that, rather than a timer and looping.使用它,而不是计时器和循环。
You can pass setState
a callback function.你可以通过setState
一个回调函数。
Example例子
this.setState({ pending: true }, () => {
console.log('State set completed for pending');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.