2016-09-15 78 views
0

發生了一些奇怪的事情。我使用foundation switch作爲我的複選框。無法獲取正確的複選框狀態

當我在反應瀏覽器工具上查看我的狀態時,我的檢查狀態爲true。當我在控制檯中記錄狀態時,它是錯誤的。錯誤在哪裏?

ES6:

constructor(props){ 
    super(props); 
    this.state = { 
    checked: false 
    }, 
    this._handleChange = this._handleChange.bind(this) 
} 

_handleChange(){ 
    this.setState({ checked: !this.state.checked }); 
    console.log(this.state.checked); // becomes the opposite the state! 
} 

渲染:

<div className="switch"> 
    <input className="switch-input" id="exampleSwitch" type="checkbox" onChange={this._handleChange} checked={this.state.checked} name="exampleSwitch"> 
    <label className="switch-paddle" htmlFor="exampleSwitch"> 
    <span className="show-for-sr">Download Kittens</span> 
    </label> 
</div> 

點擊時,我的反應控制檯顯示它作爲true但在控制檯,它的falseconsole.log()顯示與該州相反。如果狀態爲false,則日誌顯示true。任何原因?

編輯爲另一個方法:

_onSubmit(){ 
let checked = this.state.checked; 
$.ajax({ 
    ... 
    data: {"checked": checked }, 
    ... 
}); 
} 

回答

1

從陣營documentation

的setState()不立即發生變異this.state但創建 未決狀態轉變。調用 方法後訪問this.state可能會返回現有值。

因此console.log()可能在這裏以意想不到的方式工作。爲了得到正確的結果,你可能想第二個參數傳遞到您的setState()

第二個參數(可選)是一個回調函數,這將是一次 的setState完成執行和組件進行重新渲染。

_handleChange(){ 
    this.setState({ checked: !this.state.checked },() => { 
    console.log(this.state.checked); // output will be as expected 
    }); 
} 
+0

啊。好。但我需要知道,如果狀態是錯誤的,我可以用ajax發送。 – Sylar

+0

謝謝。在使用ajax調用的另一種方法中,我可以安全地使用'this.state.checked'? – Sylar

+0

@Sylar請更新你的問題,我不知道你在說什麼'另一種方法,它看起來如何等等。謝謝! –

0

的setState()不是同步的動作,因此API可以讓你給它一個回調做東西的setState()完成時的能力。以下示例代碼未經測試。文檔:Facebook setState() documentation.

var Component = React.createClass({ 
 
     getInitialState: function() { 
 
     return ({ 
 
      initialState: true 
 
     }); 
 
     }, 
 
     changeState: function() { 
 
     this.setState({ 
 
      initialState: false 
 
     }, function() { 
 
      console.log(this.state.initialState); // this is the callback 
 
     }); 
 
     }, 
 
     render: function() { 
 
      return ( 
 
      <button type="button" onClick = {this.changeState}> Test component </button> 
 
     ); 
 
    }         
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>