2017-05-07 10 views
3

사용자가 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> 
) 
} 

답변

1

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