试图理解 e.PreventDefault 和 e.StopPropogation 行为

Trying to understand e.PreventDefault and e.StopPropogation behavior

我有一个 handleSubmit 函数,它检查表单的有效性,然后根据 form.checkValidity 的结果将 validated 标志的状态设置为 true。

validated默认为false,通过表单有效性检查后,使用setValidated设置为true。

问题是,当我使用 e.StopPropogation 时,这会阻止其余代码的执行吗?

validated 的值在 handleSubmit 函数的末尾打印 false,这表明未调用 setValidated 钩子(但 console.log 继续打印? ).此外,查看我的控制台输出,程序跳回到第 50 行并且 validated 的值是 true。

不太明白为什么第50行在handleSubmit之后执行,为什么validated的值会是true?

import Form from "react-bootstrap/Form"
import Button from "react-bootstrap/Button"
import Col from "react-bootstrap/Col"
import { useState } from "react"


const Register = () => {

    const [validated, setValidated] = useState(false);
    const [visitorId, setVisitorId] = useState('');
    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');
    const [lastFourDigits, setLastFourDigits] = useState('');
    const [mobileNumber, setMobileNumber] = useState('');
    /*const [email, setEmail] = useState(''); Note: for future addition */
    const [startDate, setStartDate] = useState('');
    const [endDate, setEndDate] = useState('');

    /*const[visit, setVisit] = useState([]);*/

    const visit = {
        firstName : firstName,
        lastName : lastName,
        lastFourDigits : lastFourDigits,
        mobileNumber : mobileNumber,
        startDate: startDate,
        endDate : endDate
    }
    

    const addVisit = async (visit) => {
        const res = await fetch('http://localhost:8080/api/register-scheduled-visit',{
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
            },
            body: JSON.stringify(visit), 
        })

   /* const addVisitor = async (visit) => {
        const res = await fetch('http://localhost:8080/api/register-new-visitor',{
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
            },
            body: JSON.stringify(visit), 
        })  */

    }
    console.log("Validated outside handleSubmit: " + validated)
    const handleSubmit = (event) => {
       
        const form = event.currentTarget;
        console.log("Form validaity in handlesubmit: " + form.checkValidity())
        console.log("Validated inside handleSubmit first line: " + validated)
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }

        /*setVisit({...visit, startDateofVisit: startDate, endDateOfVisit: endDate, visitorId: '1', oneTimeUse: false});*/
        console.log(visit);
        setValidated(true);
        console.log("Validated in handlesubmit second line: " + validated)
        /*event.preventDefault();*/
      };
    console.log(visit);
    console.log('First Name: ' + firstName);
    console.log('Last Name: ' + lastName);
    
    return (
        <div className="register-form">
            <h1>Register a visitor</h1>
            <Form noValidate validated={validated} onSubmit={handleSubmit} style={{textAlign:'left'}}>
            <Form.Row>
                <Form.Group as={Col} controlId="formGridFirstName">
                <Form.Label>First name</Form.Label>
                <Form.Control 
                    required 
                    type="text" 
                    placeholder="First name" 
                    defaultValue={firstName} 
                    onChange={(e) => setFirstName(e.target.value)}/>
                <Form.Control.Feedback type="invalid">Please provide a name</Form.Control.Feedback>
                </Form.Group>

                <Form.Group as={Col} controlId="formGridLastName">
                <Form.Label>Last name</Form.Label>
                <Form.Control 
                    required type="text" 
                    placeholder="Last name" 
                    defaultValue={lastName} 
                    onChange={(e) => setLastName(e.target.value)}/>
                <Form.Control.Feedback type="invalid">Please provide a name</Form.Control.Feedback>
                </Form.Group>
            </Form.Row>

            <Form.Group controlId="formGridLastFourDigits">
                <Form.Label>Last four digits of identification</Form.Label>
                <Form.Control 
                    required
                    placeholder="123A"
                    defaultValue={lastFourDigits}
                    onChange={(e) => setLastFourDigits(e.target.value)}/>
                <Form.Control.Feedback type="invalid">Please provide the last four digits of your identification</Form.Control.Feedback>
            </Form.Group>

            <Form.Group controlId="formGridMobileNumer">
                <Form.Label>Mobile number</Form.Label>
                <Form.Control 
                    required
                    placeholder="Mobile number"
                    defaultValue={mobileNumber}
                    onChange={(e) => setMobileNumber(e.target.value)} />
                    <Form.Text id="mobileHelp" muted>
                        A QR code will be sent to this number for entry.
                    </Form.Text>
                <Form.Control.Feedback type="invalid">Please provide your mobile number</Form.Control.Feedback>
            </Form.Group>

            <Form.Row>
                <Form.Group as={Col} controlId="formGridStartDate">
                <Form.Label>Start date of visit</Form.Label>
                <Form.Control 
                    required 
                    type="date"
                    defaultValue={startDate}
                    onChange={(e)=> setStartDate(e.target.value)}/>
                <Form.Control.Feedback type="invalid"></Form.Control.Feedback>
                </Form.Group>

                <Form.Group as={Col} controlId="formGridEndDate">
                <Form.Label>End date of visit</Form.Label>
                <Form.Control 
                    required 
                    type="date"
                    defaultValue={endDate}
                    onChange={(e)=> setEndDate(e.target.value)}/>
                <Form.Control.Feedback type="invalid"></Form.Control.Feedback>
                </Form.Group>
            </Form.Row>

            <Button variant="primary" type="submit">
                Submit
            </Button>
        </Form>
        </div>
    )
}

export default Register

控制台输出

log.js:24 [HMR] Waiting for update signal from WDS...
Register.js:50 Validated outside handleSubmit: false
Register.js:67 {firstName: "", lastName: "", lastFourDigits: "", mobileNumber: "", startDate: "", …}
Register.js:68 First Name: 
Register.js:69 Last Name: 

Register.js:54 Form validaity in handlesubmit: false
Register.js:55 Validated inside handleSubmit first line: false
Register.js:62 {firstName: "", lastName: "", lastFourDigits: "", mobileNumber: "", startDate: "", …}
Register.js:64 Validated in handlesubmit second line: false
Register.js:50 Validated outside handleSubmit: true
Register.js:67 {firstName: "", lastName: "", lastFourDigits: "", mobileNumber: "", startDate: "", …}
Register.js:68 First Name: 
Register.js:69 Last Name: 

Question is, when I use e.StopPropogation, does this stop the rest of the code from executing?

不,它会阻止事件传播和触发其他 submit 事件侦听器更高层 DOM(注意:你不太可能有任何事件侦听器)。 (另一方面,preventDefault 会阻止表单的默认行为:将表单数据提交到 action 并导航到响应生成的新页面)。

The value of validated prints false at the end of the handleSubmit function, which suggests the setValidated hook was not called (but console.log continues to print?). In addition, looking at my console output, the program jumps back to line 50 and the value of validated there is true.

handleSubmit 已关闭 validated 常量。它永远不会改变它的价值。

setValidated 将排队更改组件的状态。一旦事件循环空闲(即 handleSubmit 完成 运行 后的某个时间,假设浏览器由于表单提交而没有导航到新页面),组件将被重新呈现。这将再次调用 Register 函数,并且属于此函数调用的 validated 常量将具有新值。

I don't quite understand why line 50 executes after handleSubmit and why would the value of validated there be true?

这就是我上一段中描述的重新渲染。