2017-07-08 99 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;