我想知道在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á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>
)
}
谢谢。
isRunning
,当你启动计时器时将其设置为true
,当计时器结束时将其设置为false
,并且除非isRunning
为 false,否则不允许启动计时器。 - nem035