javascript - ReactJS 中的 setState 函数不是设置状态。如何克服这个问题呢?

标签 javascript reactjs events

要打开引导模式,我设置状态 {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>&nbsp;{name}
      </div>);
      case 'Full Day': return (<div className={`fullday ${isApproved}`} title= 
       {eventType}>
        <i className="fas fa-umbrella-beach"></i>&nbsp;{name}&nbsp;
       <i style={{ marginTop: '-2px', position: 'absolute' }} >
          <a onClick={this.onClickdialog.bind(this)} style={{ fontWeight: 
       'bold' }}>...</a></i>
      </div>);
      default: return (<div>{eventType}:&nbsp;{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/

相关文章:

javascript - jQueryUI 和 jQuery 插件冲突

javascript - 如何使用从 Google Analytics 检索的数据并将其显示在 Google 图表中

javascript - 为什么在 javascript 生成器中生成变异对象在转换为数组时会导致不同的行为?

javascript - 如何使用 Set 和 react 的 useState?

javascript - 进入 Spotify 阵列

Delphi CreateOleObject 事件

c# - 如何防止事件导致其自身的事件在 C# 中触发?

javascript - 防止对象函数内的事件覆盖 "this"

javascript - 我们如何从 JSON 响应中访问包含连字符的数据?

javascript - useEffect 中异步函数的 React Hook 警告 : useEffect function must return a cleanup function or nothing