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