具有箭头函数es6的setTimeout ReactJS

Raf*_*ora 22 javascript settimeout reactjs

我想知道如何setTimeout()在ReactJS 上使用,因为我这样做:

 timerid = setTimeout( () => this.reqMaq( obj['fkmaqid'] ), 2000 )
Run Code Online (Sandbox Code Playgroud)

它调用两次函数this.reqMaq().

如何阻止第一次通话?并且只是在时间之后保持通话?

这是组件:

reqMaq (maqid) {
    return fetch(`/scamp/index.php/batchprodpry/${maqid}`, {credentials: 'same-origin'})
      .then(req => {
        if (req.status >= 400) {
          throw new Error("Bad response from server")
        }
        return req.json()
      })
      .then(json => this.processMaqReq(json))
      .catch(function(error) {
        console.log('request failed', error)
      })
  }    

  handleChangeMaq (event) {
    event.preventDefault()
    if (event.target.value.length > 0) {
      let obj = this.state.obj
      obj['fkmaqid'] = VMasker.toPattern(event.target.value, "99-99-99-99")
      // if (timerid) {
      //   clearTimeout(timerid)
      // }
      // timerid = setTimeout(() => {
      //   if (!isRunning) {
      //     this.reqMaq(obj['fkmaqid'])
      //   }
      // }, 2000)
      const fx = () => this.reqMaq( obj['fkmaqid'] )
      timerid = setTimeout( fx, 2000 )
      this.setState({ obj: obj })
    }
  }
  render() {
    return (
      <div className="form-group">
              <label htmlFor="maquina">M&aacute;quina</label>
              <input type="text" className="form-control" id="maquina"
                name="maquina"
                placeholder="Maquina"
                value={this.state.obj['fkmaqid'] || ''}
                onChange={this.handleChangeMaq}
                ref={node => {
                  input1 = node
                }}
                required="required"
              />
            </div>
    )
  }
Run Code Online (Sandbox Code Playgroud)

谢谢.

Meh*_*var 45

试试这个:

if (timerid) {
  clearTimeout(timerid);
}

timerid = setTimeout(() => {
  this.reqMaq(obj['fkmaqid'])
}, 2000);
Run Code Online (Sandbox Code Playgroud)