Dan*_*Dan 42 html javascript event-handling reactjs
好的,我会尽快做到这一点,因为它应该是一个简单的解决方案......
我读了很多类似的问题,答案似乎很明显.从来没有什么我不得不抬头看!但是......我有一个错误,我无法理解如何解决或为什么会发生这种情况.
如下:
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}/>
)
}
Run Code Online (Sandbox Code Playgroud)
更多代码围绕着这个,但这就是我的问题所在.应该工作吧?
我也试过这个:
handleOnChange = (event) => {
if(event.target.className == "barClubLounge") {
this.setState({barClubLounge: !this.state.barClubLounge});
console.log(event.target.checked)
console.log(this.state.barClubLounge)
}
Run Code Online (Sandbox Code Playgroud)
所以我有两个console.log(),都应该是一样的.我确实将状态设置为与event.target.checked它上面的行相同!
但它总是与它应该的相反.
我使用时也一样!this.state.barClubLounge; 如果它开始为假,在我第一次点击它仍然是假的,即使复选框是否被选中是基于状态!!
这是一个疯狂的悖论,我不知道最新情况,请帮忙!
May*_*kla 48
原因是setState是异步的,你不能指望state刚刚更新后的值setState,如果你想检查值使用一个callback方法.将一个方法作为回调传递,该方法将在setState完成其任务后执行.
为什么setState是异步的?
这是因为setState改变state并导致重新渲染.这可能是一项昂贵的操作,并且synchronous可能使浏览器无法响应.因此,setState调用asynchronous以及更好的UI体验和性能都可以进行批处理.
来自Doc:
setState()不会立即改变this.state,但会创建挂起状态转换.调用此方法后访问this.state可能会返回现有值.无法保证对setState的调用进行同步操作,并且可以对调用进行批处理以获得性能提升.
使用setState的回调方法:
要在state之后检查更新后的值setState,请使用如下所示的回调方法:
setState({ key: value }, () => {
console.log('updated state value', this.state.key)
})
Run Code Online (Sandbox Code Playgroud)
检查一下:
class NightlifeTypes extends React.Component {
constructor(props) {
super(props);
this.state = {
barClubLounge: false,
seeTheTown: true,
eventsEntertainment: true,
familyFriendlyOnly: false
}
}
handleOnChange = (event) => { // Arrow function binds `this`
let value = event.target.checked;
if(event.target.className == "barClubLounge") {
this.setState({ barClubLounge: value}, () => { //here
console.log(value);
console.log(this.state.barClubLounge);
//both will print same value
});
}
}
render() {
return (
<input className="barClubLounge" type='checkbox' onChange={this.handleOnChange} checked={this.state.barClubLounge}/>
)
}
}
ReactDOM.render(<NightlifeTypes/>, document.getElementById('app'))Run Code Online (Sandbox Code Playgroud)
<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>
<div id='app'/>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6112 次 |
| 最近记录: |