Javascript 超时后自动保存到数据库
我想在用户在React组件中填写表单时执行自动保存。ajax调用应该在上次Javascript 超时后自动保存到数据库,javascript,reactjs,timeout,autosave,Javascript,Reactjs,Timeout,Autosave,我想在用户在React组件中填写表单时执行自动保存。ajax调用应该在上次onChange事件发生3秒后触发 我下面的代码就是从中得到启发的,它展示了如何使用setTimeout和cleartimout来完成这一任务。但是我在React实现中做了一些错误的事情——输入时3秒的延迟没有得到尊重 有什么想法吗?还是我对如何解决这个问题的想法都错了? class Form extends Component { constructor() { super(); this.state
onChange
事件发生3秒后触发
我下面的代码就是从中得到启发的,它展示了如何使用setTimeout
和cleartimout
来完成这一任务。但是我在React实现中做了一些错误的事情——输入时3秒的延迟没有得到尊重
有什么想法吗?还是我对如何解决这个问题的想法都错了?
class Form extends Component {
constructor() {
super();
this.state = {
isSaved: false
};
this.handleUserInput = this.handleUserInput.bind(this);
this.saveToDatabase = this.saveToDatabase.bind(this);
}
saveToDatabase() {
var timeoutId;
this.setState({isSaved: false});
if (timeoutId) {
clearTimeout(timeoutId)
};
timeoutId = setTimeout( () => {
// Make ajax call to save data.
this.setState({isSaved: true});
}, 3000);
}
handleUserInput(e) {
const name = e.target.name;
const value = e.target.value;
this.setState({[name]: value});
this.saveToDatabase();
}
render() {
return (
<div>
{this.state.isSaved ? 'Saved' : 'Not saved'}
// My form.
</div>
)
}
类表单扩展组件{
构造函数(){
超级();
此.state={
isSaved:错
};
this.handleUserInput=this.handleUserInput.bind(this);
this.saveToDatabase=this.saveToDatabase.bind(this);
}
saveToDatabase(){
var-timeoutId;
this.setState({isSaved:false});
if(超时ID){
clearTimeout(超时ID)
};
timeoutId=setTimeout(()=>{
//进行ajax调用以保存数据。
this.setState({isSaved:true});
}, 3000);
}
手动输入(e){
const name=e.target.name;
常量值=e.target.value;
this.setState({[name]:value});
这是saveToDatabase();
}
render(){
返回(
{this.state.isSaved?'Saved':'notsaved'}
//我的表格。
)
}
在saveToDatabase
方法中,每次调用该方法时,您都在定义一个新的未定义的timeoutId
变量。这就是if
语句从未被调用的原因
相反,您需要确定变量的范围,并在构造函数中创建类数据属性
constructor() {
super();
this.state = {
isSaved: false
};
this.timeoutId = null;
this.handleUserInput = this.handleUserInput.bind(this);
this.saveToDatabase = this.saveToDatabase.bind(this);
}
saveToDatabase() {
this.setState({isSaved: false});
if (this.timeoutId) {
clearTimeout(this.timeoutId)
};
this.timeoutId = setTimeout( () => {
// Make ajax call to save data.
this.setState({isSaved: true});
}, 3000);
}