【发布时间】:2017-10-05 10:45:51
【问题描述】:
当用户在 React 组件中填写表单时,我想执行自动保存。自上次onChange 事件后 3 秒后,应触发 ajax 调用。
我下面的代码灵感来自an instructive article,它展示了如何使用setTimeout 和clearTimeout 完成此操作。但是我在我的 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>
)
}
【问题讨论】:
标签: javascript reactjs timeout autosave