javascript - setTimeout 没有按预期工作 React Native
问题描述
我试图在 React Native 中 40 秒后调用一个函数。但似乎无论我什么时候在 15 到 18 秒内设置函数调用。尝试了几种解决方案,但运气不好。
我的完整代码如下:
export default class OpenLocker extends Component {
constructor(props) {
super(props)
this.state = {
disable: false,
}
}
openBox() {
const data = {
model: this.props.model,
machine_id: this.props.machine_id,
locker_id: this.props.locker_id,
}
const { model, machine_id, locker_id } = data
const this_url = window.location.href
const parse_url = url.parse(this_url, true, true)
const host = parse_url.protocol + "//" + parse_url.host
const api_url = `${host}/vendor/locker/open/${model}/${machine_id}/${locker_id}`
axios
.get(api_url)
.then((response) => {
if (!response.data) {
alert("Box open failed!")
} else {
this.setState({
disable: true,
})
setTimeout(() => {
this.closeBox(data, host).bind(this)
}, 40000)
}
})
.catch((error) => {
alert(error)
})
}
closeBox(data, host) {
const { model, machine_id, locker_id } = data
const api_url = `${host}/vendor/locker/close/${model}/${machine_id}/${locker_id}`
axios
.get(api_url)
.then((response) => {
if (!response.data) {
alert("Box close failed!")
} else {
this.setState({
disable: false,
})
alert("Box opened successfully")
}
})
.catch((error) => {
alert(error)
})
}
render() {
return (
<div>
<button
disabled={this.state.disable}
id="open-box"
type="button"
className="btn btn-secondary btn-block text-white"
onClick={this.openBox.bind(this)}
>
Open Box
</button>
</div>
)
}
}
如何closeBox
在 40 秒后调用函数,或者为什么 setTimeout() 不能按我预期的方式工作?需要你的建议。提前致谢。
解决方案
推荐阅读
- automated-tests - 如何访问 selenium IDE 中的 chrome 确认框
- python - 如何使用pyodbc和带有python的sql server从数据库中检索数据
- c# - 无法在 C# 中创建模拟约会
- html - 如果容器可滚动,如何将元素粘贴到其容器底部?
- sql - 如何在使用 TFS/Azure Devops 部署期间将文件放在文件系统上,以便部署后脚本可以找到它
- c# - 如何在 RockBlock 网络服务器中为应用程序脚本配置 URL 以及如何通过来自 RockBlock 服务器的 HTTP_Post 请求脚本接收数据
- java - 如何将 Listview 项目作为附件发送到电子邮件,最好是 csv(android studio java)?
- php - 重定向后如何保存网站引荐来源网址
- tensorflow - 我可以同时安装 tensorflow 和 tensorflow lite 吗?
- php - Yii 框架文件上传