首页 > 解决方案 > 如何在更改值之前使 Switch 组件异步等待成功响应?

问题描述

开关的默认流程将在按下时立即切换值。

我想执行以下逻辑

  1. 按下开关
  2. 暂时不要更改值
  3. 打开警报框
  4. 如果没问题,发送 post 请求以切换数据库值
  5. 成功响应后,允许开关值更改

我可以获得成功的响应并更新开关,但是一旦按下开关,值就会切换两次,我想暂停此行为,直到有成功的响应。尝试过异步等待,尝试将开关包装在可触摸的无反馈中......现在需要一些帮助

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

标签: javascriptreact-native

解决方案


更改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}/>

小吃示例


推荐阅读