紅糖糍粑
2019-06-05 16:01:49
為什么調(diào)用setState方法不立即改變狀態(tài)?好吧,我試著快點(diǎn),因?yàn)檫@應(yīng)該是個(gè)簡單的解決辦法.我讀過許多類似的問題,答案似乎很明顯。從一開始我就沒必要抬頭看了!但是.。我有一個(gè)錯(cuò)誤,我不知道如何修復(fù)或它發(fā)生的原因。詳情如下: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}/>
)}更多的代碼圍繞著這一點(diǎn),但這正是我的問題所在。應(yīng)該管用,對吧?我也試過這樣做:handleOnChange = (event) => { if(event.target.className == "barClubLounge") {
this.setState({barClubLounge: !this.state.barClubLounge});
console.log(event.target.checked)
console.log(this.state.barClubLounge)}所以我有那兩個(gè)人console.log()兩者應(yīng)該是相同的。我實(shí)際上是將狀態(tài)設(shè)置為與event.target.checked在上面的那條線上!但是它總是返回它應(yīng)該返回的相反的東西。當(dāng)我使用!this.state.barClubLounge如果它啟動(dòng)為false,則在我第一次單擊時(shí),它仍然是false,即使復(fù)選框是否選中也是基于狀態(tài)的!這是一個(gè)瘋狂的悖論,我不知道發(fā)生了什么,請幫助!
3 回答

白衣染霜花
TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊
handleOnChange = (event) => { let inputState = event.target.checked; if(event.target.className == "barClubLounge") { this.setState({ barClubLounge: inputState}, () => { //here console.log(this.state.barClubLounge); //here you can call other functions which use this state variable // }); } }

狐的傳說
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
添加回答
舉報(bào)
0/150
提交
取消