gpt4 book ai didi

javascript - setTimeout ReactJS 与箭头函数 es6

转载 作者:行者123 更新时间:2023-12-03 13:02:30 24 4
gpt4 key购买 nike

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

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

它调用了两次函数 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>
)
}

谢谢。

最佳答案

试试这个:

if (timerid) {
clearTimeout(timerid);
}

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

关于javascript - setTimeout ReactJS 与箭头函数 es6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38976955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com