确保onPress功能的方法只能被点击一次?

时间:2017-10-21 05:17:57

标签: reactjs react-native

我尝试过使用信号量这样的概念:

  • 检查this.state.clicked的函数,如果为true,则返回而不执行逻辑,如果不是:
  • this.state.clicked设置为true。
  • 函数执行逻辑。
  • this.state.clicked设置为false。

这通常有效,但在极端情况下,当可点击垃圾邮件被发送时,所有事件之间都会出现某种竞争条件,有时候我会得到两次函数逻辑。

需要视觉效果的代码示例:

<ClickableComponent onPress={() => { 
     if (this.state.clicked) return;
     this.state.clicked = true;
     // Execute logic here
     // This logic sometime gets executed twice when the clicking is fast enough
     this.state.clicked = false;
     }}
} />

有关不同方法的任何想法吗?

1 个答案:

答案 0 :(得分:2)

您无法直接设置state。您必须在setState回调中执行逻辑。

<ClickableComponent onPress={() => { 
  if (this.state.clicked) return;

  this.setState({ clicked: true }, () => {
    // Execute logic here
    this.setState({ clicked: false });
  });
} />