简体   繁体   中英

Calling function from Hook Modal in React Js

I am trying to call the function(update state) from modal hook in React js. But, it does not update the state. However, when I write alert inside the function it works but setState does not. What can be a problem????

Main Component

this.state = {
      message: false
}

showMessage(){
  alert(" hhh");  //works
  // this.setState({message:true})  //does not work
}

<ExcludeHolidayModal confirmExHol={this.showMessage}/>

Modal

function ExcludeHolidayModal(props) {
    const [show, setShow] = useState(false);
    const handleClose = () => setShow(false);
    const handleShow = () => {setShow(true)};
    const [date, setDate] = useState(new DateObject());

    const excludeHolidays = (dates) => {
      API.excludeHolidays(dates).then(() => {
          handleClose();
          setDate(new DateObject());
          props.confirmExHol();  //Calling function here <------------
        })
        .catch((err) => {
          if (err.status === 401) {
          }
        });
    }

    return (
      <>
        <Button onClick={handleShow} data-testid="help-button" variant="info">
            </Button>  
        <Modal
          show={show}
          onHide={handleClose}
          backdrop="static"
          keyboard={false}
        >
          <Modal.Header closeButton>
            <Modal.Title>Choose Holidays</Modal.Title>
          </Modal.Header>
          <Modal.Body>
          <DatePicker 
                value={date} 
                 onChange={setDate}
                 multiple={true}/>
          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={() => excludeHolidays(date)}>Send</Button>
          </Modal.Footer>
        </Modal>
      </>
    );
  }
  
  export default ExcludeHolidayModal;

Please try this:

this.state = {
      message: false
}

showMessage = () => {
  // alert(" hhh");  //works
  this.setState({message:true})  //does not work
}

<ExcludeHolidayModal confirmExHol={this.showMessage}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM