首页 > 解决方案 > 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() 不能按我预期的方式工作?需要你的建议。提前致谢。

标签: javascriptreactjsreact-nativeaxiossettimeout

解决方案


推荐阅读