超时后自动保存到数据库

Autosave to database after timeout

我想在用户在 React 组件中填写表单时执行自动保存。 ajax 调用应在自上次 onChange 事件后 3 秒后触发。

我下面的代码的灵感来自 an instructive article,它展示了如何使用 setTimeoutclearTimeout 来实现这一点。但是我在我的 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>
  )
}

saveToDatabase 方法中,每次调用该方法时,您都会定义一个新的 undefined timeoutId 变量。这就是为什么 if 语句永远不会被调用的原因。

相反,您需要确定变量的范围并在构造函数中创建 class 数据 属性。

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