為什么調用setState方法不立即改變狀態?好吧,我試著快點,因為這應該是個簡單的解決辦法.我讀過許多類似的問題,答案似乎很明顯。從一開始我就沒必要抬頭看了!但是.。我有一個錯誤,我不知道如何修復或它發生的原因。詳情如下:class NightlifeTypes extends Component {constructor(props) {
super(props);
this.state = {
barClubLounge: false,
seeTheTown: true,
eventsEntertainment: true,
familyFriendlyOnly: false
}
this.handleOnChange = this.handleOnChange.bind(this);}handleOnChange = (event) => {
if(event.target.className == "barClubLounge") {
this.setState({barClubLounge: event.target.checked});
console.log(event.target.checked)
console.log(this.state.barClubLounge)
}}render() {
return (
<input className="barClubLounge" type='checkbox' onChange={this.handleOnChange} checked={this.state.barClubLounge}/>
)}更多的代碼圍繞著這一點,但這正是我的問題所在。應該管用,對吧?我也試過這樣做:handleOnChange = (event) => { if(event.target.className == "barClubLounge") {
this.setState({barClubLounge: !this.state.barClubLounge});
console.log(event.target.checked)
console.log(this.state.barClubLounge)}所以我有那兩個人console.log()兩者應該是相同的。我實際上是將狀態設置為與event.target.checked在上面的那條線上!但是它總是返回它應該返回的相反的東西。當我使用!this.state.barClubLounge如果它啟動為false,則在我第一次單擊時,它仍然是false,即使復選框是否選中也是基于狀態的!這是一個瘋狂的悖論,我不知道發生了什么,請幫助!
為什么調用setState方法不立即改變狀態?
紅糖糍粑
2019-06-05 16:01:49