2017-07-08 96 views
0

我的应用很简单:一个按钮有一个状态toggleButton。在构造函数toggleButton中设置为默认值false。当我按下按钮时,应用程序将开始记录一些传感器和他们的数据到Chrome调试器屏幕。切换按钮第一次不跳转

constructor(props) { 
    super(props); 
    this.state = { 
     toggleButton: false 
    }; 
} 

recordSensors() { 
    let toggleButton = !this.state.toggleButton; 
    this.setState({ toggleButton }); 

    if (this.state.toggleButton) { 
     // start & record some sensors data 
    } else { 
     // stop recording 
    } 
} 

render() { 
    return (
     <View style={styles.container}> 
     <TouchableOpacity 
      style={styles.toggleButton} 
      onPress={() => this.recordSensors()} 
     > 
      <Text style={styles.buttonText}> 
      {this.state.toggleButton ? 'Stop' : 'Start'} 
      </Text> 
     </TouchableOpacity> 
     <Text> 
      {this.state.toggleButton ? 'Recording...' : null} 
     </Text> 
     </View> 
    ); 
    } 

奇怪的是,我第一次按下按钮,其文本改为StopRecording...文本出现,但应用程序没有记录传感器的数据。当我再次按下按钮(第二次)时,它现在会记录下来。

但是,如果我将if (this.state.toggleButton)更改为那么它工作正常。我无法理解它的逻辑了。你们能帮忙吗?

+1

[状态更新可以是异步的(https://facebook.github.io/react/docs/state- and-lifecycle.html#state-updates-may-be-asynchronous),你的状态可能在你执行if语句的时候没有被更新 –

回答

2

您正在使用

let toggleButton = !this.state.toggleButton; 

toggleButtonthis.state.toggleButton

逆值,如果说,this.state.toggleButtonfalse然后toggleButton将有true作为其值。所以,你要指定的状况完全不同,这里

if (this.state.toggleButton) //if(false) 

当你这样做

if(toggleButton) //if(true) 

所以,当你有this.state.toggleButtonfalse,反之亦然

+0

但是我在'let toggleBitton =!this.state后改变了状态。 toggleButton',在那行之后,状态应该与之前的任何情况相反? –

+0

你是什么意思。你可以请添加更多的细节。 –

+0

因此,第一次切换状态为false时,在'record'函数中,我创建了一个变量toggleButton,其值为切换状态的倒数。然后我设置反转状态的倒数值。所以在记录函数中的两行之后,状态应该被反转。 –

0

您的问题,注意到条件:

onPress={() => this.recordSensors()} 

修复:

onPress={() => this.recordSensors} 

这里是你的逻辑:

在你的构造:

toggleButton = false; 

在渲染:

onPress={() => this.recordSensors()} 

的呼叫:

//currently this.state.toggleButton == false; 
let toggleButton = !this.state.toggleButton; // let toggleButton=true; 
this.setState({ toggleButton }); // now state.toggleButton = true; 

所以现在,当您点击按钮,你在乎通话recordSensors()第二次:

//currently this.state.toggleButton == true; 
let toggleButton = !this.state.toggleButton; // let toggleButton =false; 
this.setState({ toggleButton }); // now state.toggleButton == false;