javascript - 如何在更改值之前使 Switch 组件异步等待成功响应?
问题描述
开关的默认流程将在按下时立即切换值。
我想执行以下逻辑
- 按下开关
- 暂时不要更改值
- 打开警报框
- 如果没问题,发送 post 请求以切换数据库值
- 成功响应后,允许开关值更改
我可以获得成功的响应并更新开关,但是一旦按下开关,值就会切换两次,我想暂停此行为,直到有成功的响应。尝试过异步等待,尝试将开关包装在可触摸的无反馈中......现在需要一些帮助
<Switch
value={this._getSwitchValue(id)}
onValueChange={() => this._toggleSwitch(id)}
/>
/**
* Toggle the Switch - Send post request to database
*/
_toggleSwitch (id) {
Alert.alert('Notice!', 'Do you really want to change this setting?',
[
{ text: "OK", onPress: () => this.props.toggleSettingsSwitch(id, this.props.token) },
{ text: "Cancel", onPress: () => console.log("cancel pressed")}
],
{ cancelable: true }
)}
解决方案
更改Switch
发出请求的函数内的值。
toggleSettingsSwitch = async (value) => {
const response = await this.changeSettingsRequest(); // making a call
// here add a check, if request was successful change switch value
// if (response.ok) {
// this.setState({ switchValue: value });
//}
};
_toggleSwitch = (value) => {
Alert.alert(
'Notice!',
'Do you really want to change this setting?',
[
{
text: 'OK',
onPress: () => {
this.toggleSettingsSwitch(value);
},
},
{ text: 'Cancel', onPress: () => console.log('cancel pressed') },
],
{ cancelable: true }
);
};
<Switch
onValueChange={this._toggleSwitch}
value={this.state.switchValue}/>
推荐阅读
- hashmap - 用另一个 HashMap 的内容扩展 HashMap
- java - 使用 Spring 和 Parameterized 运行 JUnit
- c# - 如何手动信任嵌入在我的应用程序中的自签名证书?
- python - 遍历多个数据框并根据特定列执行计算
- angularjs - 如何修复我的代码?angularjs,ejs代码
- angular - 如何在 Angular 5 或更高版本中以编程方式获取 formControlName
- javascript - Javascript 使用 document.onclick 关闭下拉菜单
- firebase - 为什么这个 push() 覆盖而不是添加?
- css - 难以掌握 react 或 CSS 的用法
- javascript - 如何在javascript中检查时间是否已到第二天或过去一天?