当用户单击列表中的项目时,我尝试显示/隐藏模式。该模式按计划显示,但无法隐藏。当_dismiss()
被调用时,setState
执行,但是当我console.log
回调中的state
时,参数 show
仍为 true。
为什么会发生这种情况?
Message.jsx
export default class Message extends React.Component {
constructor(props) {
super(props);
this.state = {
show: false
};
this._onClick = this._onClick.bind(this);
this._dismiss = this._dismiss.bind(this);
}
_onClick(e) {
e.preventDefault();
this.setState({
show: true
})
}
_dismiss() {
this.setState({
show: false
}, function () {
console.log(this.state) // logs: Object {show: true}
})
}
render() {
return (
<div onClick={this._onClick} className="message">
<Modal show={this.state.show} close={this._dismiss}>
<h1>...</h1>
</Modal>
</div>
);
}
}
Modal.jsx
export default class Modal extends React.Component {
constructor(props) {
super(props);
this._onClose = this._onClose.bind(this);
}
_onClose() {
this.props.close()
}
render() {
if (this.props.show) {
return (
<div className="modal" onClick={this._onClose} >
<div className="content">
{this.props.children}
</div>
</div>
);
} else {
return null
}
}
}
最佳答案
当单击其子项时,该 div 仍会发生 onClick
事件。我怀疑 _dismiss
正在被调用,然后 _onClick
正在被调用。 React 批处理 setState
调用,因此最终将 show
设置回 true
。
补救措施。
如果处理程序的关闭回调为您提供事件作为参数。调用 e.stopPropagation()
或来自注释中的 @richsilv e.stopImmediatePropagation()
。
或者如果它没有通过事件。检查 _onClick
是否 show
为 true 或 false。如果是 true,则不要 setState
关于javascript - 为什么setState后State不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43188205/