【问题标题】:Autosave to database after timeout超时后自动保存到数据库
【发布时间】:2017-10-05 10:45:51
【问题描述】:

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

我下面的代码灵感来自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>
  )
}

【问题讨论】:

    标签: javascript reactjs timeout autosave


    【解决方案1】:

    saveToDatabase 方法中,每次调用该方法时,您都在定义一个新的undefined 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);
     }
    

    【讨论】:

      猜你喜欢
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 2014-02-28
      • 1970-01-01
      • 2014-03-30
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多