[英]How to debounce the changes in a form after setState is done
很難弄清楚這一點。 前幾天,其他一些人幫助我消除了抖動,但事實證明,我現在實際上在每次擊鍵時都在消除抖動,這會導致打字時出現無法接受的延遲。
所以首先,我在我的 handleChange 方法中添加了 debounce,因為如果你輸入的速度非常快,你可以移動到另一個字段並繼續前進,第一個字段不會更新它的狀態。
然后,我為每個元素設置了一個超時時間,這樣即使你繼續前進,它也會完成。 但后來我注意到打字時出現了令人無法接受的延遲。
我對如何讓它更新狀態感到非常困惑,即使用戶已經繼續前進並繼續在下一個字段中輸入,以及在輸入中斷時自動保存到 db 也是如此。
// editingTimeout should be an object in the state
handleChange = (e) => {
const targetName = e.target.name;
const targetValue = e.target.value;
this.setState(state => {
clearTimeout(this.state.editingTimeout[targetName]);
return ({
editing: false,
editingTimeout: {
...state.editingTimeout,
[targetName]: setTimeout(() => {
console.log(`${targetName}: ${targetValue}`);
this.setState({
[targetName]: targetValue,
});
}, 300),
}
})
});
};
為了將表單的變化去抖到 api,你不需要去抖狀態更新,而是在狀態變化時調用的 api 調用。 我所做的是,更新狀態,然后調用一個函數,將更改發送到服務器,如下所示:
import debounce from 'debounce';
class ComponentA extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
}
}
handleInputChange = (e) => {
this.setState({ [e.target.name]: e.target.value }, () => this.update())
}
update = debounce(() => {
const data = {
name: this.state.name,
email: this.state.email,
}
this.props.updateApiCall(data);
}, 1000);
render () {
return (
<div>
<input name='name' onChange={this.handleInputChange} value={this.state.name} />
<input name='email' onChange={this.handleInputChange} value={this.state.email} />
</div>
)
}
}
在這個 wat 中,用戶更新哪個字段並不重要,去抖動只會應用於 api 調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.