Javascript 带箭头函数 es6 的 setTimeout ReactJS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38976955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:04:41  来源:igfitidea点击:

setTimeout ReactJS with arrow function es6

javascriptreactjssettimeout

提问by Rafael Mora

I'd like to know how to use setTimeout()on ReactJS, because I'm doing this:

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

 timerid = setTimeout( () => this.reqMaq( obj['fkmaqid'] ), 2000 )

and it calls twice the function this.reqMaq().

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

How do I prevent the first call? and just keep the call afterthe time?

如何防止第一个电话?并在时间之后保持通话?

Here it's the Component:

这是组件:

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>
    )
  }

Thank you.

谢谢你。

回答by Mehdi Namvar

Try this:

尝试这个:

if (timerid) {
  clearTimeout(timerid);
}

timerid = setTimeout(() => {
  this.reqMaq(obj['fkmaqid'])
}, 2000);

回答by Simone Poggi

This should do the trick

这应该可以解决问题

const fx = () => this.reqMaq( obj['fkmaqid'] )
timerid = setTimeout( fx, 2000 )

回答by James Huddle

The reason that this.reqMak()is being called twice is subtle.

this.reqMak()被调用两次的原因很微妙。

In your example you use an actual call to reqMakto delineate your function pointer for setTimeout(). The first time it is called is when you set up setTimeout; the second time is when setTimeout()runs, 2 seconds later.

在您的示例中,您使用实际调用reqMak来描述setTimeout(). 第一次调用是在您设置时setTimeout;第二次是setTimeout()运行时,2 秒后。

The reason the suggested answer works is that it neither calls reqMak'now', nor calls it later, as the function called by setTimeout(). What it does do is pass an anonymous function ()=>{}to setTimeout()for running later. And when setTimeout()runs the function, 2 seconds later, the anonymous function calls this.reqMak(), once.

建议的答案有效的原因是它既不调用reqMak“现在”,也不像setTimeout(). 它所做的是将匿名函数()=>{}传递setTimeout()给稍后运行。当setTimeout()运行该函数时,2 秒后,匿名函数调用this.reqMak(), 一次。