簡體   English   中英

在 Axios 中反應 Bootstrap 模態彈出窗口?

[英]React Bootstrap Modal Popup in Axios?

** 添加了更多信息,我沒有顯示完整的組件 **

我目前有一個警告窗口,當填寫預訂申請表時,該窗口會在網站上彈出。 如果電子郵件已發送,則它是成功警報,如果沒有,則它會讓您知道電子郵件未發送。 我正在嘗試將這些交換到 React Bootstrap 模態窗口,但無法讓它們成功打開模態窗口,下一頁加載時沒有模態。

注意:我已經嘗試在我的表單 onSubmit 以及表單提交按鈕的 onClick() 中調用 handleShow() 但模態窗口不會以任何一種方式顯示。

export default function BookingFormPrivate() {
    const { shows, getShows } = useContext(ShowContext)
    const [ name, setName ] = useState('')
    const [ email, setEmail ] = useState('')
    const [ phone, setPhone ] = useState('')
    const [ venue, setVenue ] = useState('')
    const [ location, setLocation ] = useState('')
    const [ time, setTime ] = useState('')
    const [ url, setUrl ] = useState('https://www.')
    const [ emailBody, setEmailbody ] = useState('')
    const [ type, setType ] = useState('Private')
    const [ events, setEvents ] = useState('')
    const [ showDate, setShowDate ] = useState('')

    useEffect(() => {
        getShows()
    }, [])

    const inputs = {
        name,
        email,
        phone,
        emailBody,
        events,
        venue,
        location,
        time,
        showDate,
        url,
        type
    }

    const [showModal, setShowModal] = useState(false);
    const handleShow = () => setShowModal(true);
    const handleClose = () => setShowModal(false);

    const sendMessage = () => {
        console.log(inputs)
        axios
            .post('/sendBooking', inputs)
            .then(res => {
                if (res.data.status === 'success') {
                    return (
                        <Modal.Dialog show={showModal} onHide={handleClose}>
                            <Modal className='modal fade' id='myModal'>
                                <Modal.Header className='modal-header'>
                                    <h5 className='modal-title'>Private Booking Email Sent</h5>
                                    <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </Modal.Header>
                                <Modal.Body className='modal-body'>
                                    <p>A message about your private event has been sent, we will get back to you as soon as possible. </p>
                                </Modal.Body>
                                <Modal.Footer className='modal-footer'>
                                    <button className='btn btn-primary' data-dismiss='modal' onClick={handleClose}>Close</button>
                                </Modal.Footer>
                            </Modal>
                        </Modal.Dialog>
                    )
                } else if (res.data.status === 'fail') {
                    alert("Message failed to send, please try again.")
                }        
            })
            .catch(error => {
                console.error(error)
            })
    }
    const clearInputs = () => {
        setName('')
        setEmail('')
        setPhone('')
        setEmailbody('')
        setEvents('')
        setVenue('')
        setLocation('')
        setTime('')
        setShowDate('')
        setUrl('https://www.')
        setType('Private')

        setNewPotentialShowInfo({
            name: '',
            phone: '',
            email: '',
            emailBody: '',
            venue: '',
            location: '',
            time: '',
            date: '',
            type: 'Private',
            url: 'https://www.'
        })
    }
    const [ newPotentialShowInfo, setNewPotentialShowInfo ] = useState({
            name: '',
            phone: '',
            email: '',
            emailBody: '',
            venue: '',
            location: '',
            time: '',
            date: '',
            type: 'Private',
            url: 'https://www.'
    })
    const { addPotentialShow } = useContext(ShowContext)

    const newPotentialShowFunction = () => {
        addPotentialShow(newPotentialShowInfo)
            .then(() => {
                clearInputs()
            })
            .catch(err => console.error(err.response.data.message))
    }
    const handleSubmit = e => {
        e.preventDefault();
        sendMessage();
        newPotentialShowFunction();
        // handleShow();
    }
    const handleChange = e => {
        console.log(newPotentialShowInfo)
        const { name, value } = e.target
        setNewPotentialShowInfo(prevPotentialShow => ({
            ...prevPotentialShow,
            [name]: value
        }))
            if( name === 'name' ){
                setName(value)
            } else if ( name === 'phone' ){
                setPhone(value)
            } else if ( name === 'email' ){
                setEmail(value)
    }

    const dateChange = (date) => {
        console.log(newPotentialShowInfo)
        const dateString = date.toString()
        const shortDate = dateString.slice(0, 15)
        setEvents(shortDate)
        console.log(shortDate)
        // setDate(date)
        setNewPotentialShowInfo(prevPotentialShow => ({
            ...prevPotentialShow,
            date:shortDate
        }))
    }

    const result = shows && shows.map(dates => (dates.date))
    const checkDateDisable = (data) => {
        return result.includes(new Date(data.date).toISOString())
    }

    return(
        <div className='bookingContainer'>
            <form className='bookingForm' onSubmit={handleSubmit}>
                <h3 className='formIntro'>PLEASE FILL OUT FORM TO<br/>REQUEST A PRIVATE EVENT</h3>
                <input type='text'
                        placeholder='Full Name'
                        name='name'
                        className='formInput'
                        required='required'
                        value={name}
                        onChange={handleChange}
                />
                <input type='email'
                        placeholder='E-mail'
                        name='email'
                        className='formInput'
                        required='required'
                        value={email}
                        onChange={handleChange}
                />
                <button type='submit' className='formButton' onClick={handleShow}>
                    Submit
                </button>
            </form>
            <div className='bookingCalendarPrivate'>
                <Calendar
                    onChange={dateChange}
                    value={events.date}
                    tileDisabled={checkDateDisable}
                    calendarType="US"
                />
            </div>
        </div>
    )
}

嘗試使用 useEffect() 鈎子 ( https://reactjs.org/docs/hooks-effect.html ) 來執行 http 請求。 useEffect() 接受一個回調函數,該函數您的組件安裝到 DOM執行。 useEffect() 的第二個參數是依賴項數組。 在這種情況下,我們傳遞一個空數組,因為我假設您只需要執行此代碼塊一次。

此外,您的狀態變量需要在組件內部才能正確訪問。

const SendMessage = props => {
    const [showModal, setShowModal] = useState(false);
    const handleShow = () => setShowModal(true);
    const handleClose = () => setShowModal(false);

    useEffect(() => {
       axios
         .post('/sendBooking', inputs)
         .then(res => {
           if (res.data.status === 'success') {
              handleShow();
           } else if (res.data.status === 'fail') {
              alert("Message failed to send, please try again.");
           }
         })
    }, []);

    return (
      {showModal ? (
        <Modal.Dialog show={handleShow} onHide={handleClose}>
          <Modal className='modal fade' id='myModal'>
            <Modal.Header className='modal-header'>
              <h5 className='modal-title'>Private Booking Email Sent</h5>
              <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </Modal.Header>
            <Modal.Body className='modal-body'>
              <p>A message about your private event has been sent, we will get back to you as soon as possible. </p>
            </Modal.Body>
            <Modal.Footer className='modal-footer'>
              <button className='btn btn-primary' data-dismiss='modal' onClick={handleClose}>Close</button>
            </Modal.Footer>
          </Modal>
         </Modal.Dialog>
       ) : null}
    );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM