要打开引导模式,我设置状态 {isOpen: true} 但 setState 不会更新状态
我使用了 async/await 、 setTimeout 但没有任何效果。相同的模式在我的另一个组件中打开。
import React from 'react';
import Dialog from 'react-bootstrap-dialog'
import { Button } from 'react-bootstrap'
import { Modal } from 'react-bootstrap'
class EventComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isOpen: false
};
this.onClickdialog = this.onClickdialog.bind(this);
this.toggleModal = this.toggleModal.bind(this);
}
toggleModal = () => {
console.log('open', this.state.isOpen)
this.setState({ isOpen: !this.state.isOpen }, console.log('open',
this.state.isOpen));
}
onClickdialog() {
debugger
this.toggleModal();
// this.dialog.show('Hello Dialog!')
}
renderEvent(event) {
const eventType = event.EventType;
const name = event.Name;
const isApproved = event.IsApproved === 1 ? 'approved' : 'unapproved';
switch (eventType) {
case 'Birthday': return (<div className='birthday' title={eventType}>
<i className="fas fa-birthday-cake" ></i> {name}
</div>);
case 'Full Day': return (<div className={`fullday ${isApproved}`} title=
{eventType}>
<i className="fas fa-umbrella-beach"></i> {name}
<i style={{ marginTop: '-2px', position: 'absolute' }} >
<a onClick={this.onClickdialog.bind(this)} style={{ fontWeight:
'bold' }}>...</a></i>
</div>);
default: return (<div>{eventType}: {name}</div>);
}
}
render() {
return (
<div>
{this.renderEvent(this.props.event)}
<Modal className={"override-fade"} show={this.state.isOpen}
onClose={this.toggleModal}>
</Modal>
</div>
)
}
}
export default EventComponent;
期望 isOpen 状态在点击更新状态时发生变化
最佳答案
正如 Yanis 所说,您记录错误。 setState 的第二个参数需要是回调函数,但是您立即调用 console.log。相反,请执行以下操作:
this.setState({ isOpen: !this.state.isOpen }, () => console.log(...))
顺便说一句,您不必绑定(bind)使用箭头函数定义的类属性
关于javascript - ReactJS 中的 setState 函数不是设置状态。如何克服这个问题呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57656648/