页面在单击提交按钮时刷新而不是提交表单。

huangapple go评论64阅读模式
英文:

page refreshes instead of submitting form when submit button is clicked

问题

I am having an issue with my react.js / bootstrap app where my new users form is not submitting. I originally used e.preventDefault(), but this caused my form to not validate, so I removed it. Now, my form validates, however, when I click my submit button, the page refreshes and the form is not actually submitted. Any help would be SO appreciated!!

import React from 'react';
import { useState } from 'react';
import axios from '../../api/axios';
import Form from 'react-bootstrap/Form';
import UserList from './UserList';

function UserForm({ user, setUser }) {
    const [errMsg, setErrMsg] = useState("");

    const changeVal = async (key, value) => {
        setUser(user => ({ ...user, [key]: value }));
    }

    /*Determines whether the user being created is an admin*/
    let [isAdmin, setAdmin] = useState("true");
    /*Determines whether the user being created is a driver*/
    let [isDriver, setDriver] = useState("false");

    const handleForm = async (e) => {

       // e.preventDefault();

        if (!user.employee_id) { //If the employee ID is blank, a new user is being added.
            try {
                const newUser = {
                    is_admin: isAdmin, is_driver: isDriver, employee_first_name: user.employee_first_name, employee_last_name: user.employee_last_name,
                    employee_username: user.employee_username, employee_contact_no: user.employee_contact_no, 
                    employee_street_address: user.employee_street_address, employee_password: 'testing123', employee_city: user.employee_city, employee_state: user.employee_state, employee_zip_code: user.employee_zip_code, 
                    employee_email: user.employee_email
                };
                let data = JSON.stringify(newUser);
                console.log(data);
                const response = await axios.post('/employee', data, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }
                );
                //fetchItem();

            } catch (err) {
                setErrMsg(JSON.stringify(err));
                return;
            }
        } else {
            try {
                const newUser = {
                    employee_id: user.employee_id, is_admin: isAdmin, is_driver: isDriver, employee_first_name: user.employee_first_name, employee_last_name: user.employee_last_name,
                    employee_username: user.employee_username, employee_password: user.employee_password, employee_contact_no: user.employee_contact_no,
                    employee_street_address: user.employee_street_address,
                    employee_city: user.employee_city, employee_state: user.employee_state, employee_zip_code: user.employee_zip_code,
                    employee_email: user.employee_email
                };
                let data = JSON.stringify(newUser);
                console.log(data);
                const response = await axios.put('/employee', data, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }
                );
                //fetchItem();

            } catch (err) {
                setErrMsg(JSON.stringify(err));
                return;
            }
        }



    }

    return (

        <React.Fragment>
            {!errMsg ? <>

                <div className="form-container">
                    <div className='employee-id'>
                        <label htmlFor='ID'>EMPLOYEE #</label>
                        <input className="form-control" id="ID" readOnly value={user.employee_id}></input>
                    </div>
                    <form onSubmit={handleForm} className='employee-details' data-transport-order="form">
                        <div className='form-group'>
                            <label htmlFor='UserFName'>* FIRST NAME</label>
                            <input type="text" className="form-control" id="employee_first_name" required value={user.employee_first_name} onChange={(e) => changeVal(e.currentTarget.id, e.currentTarget.value)}></input>
                            <label htmlFor='UserLName'>* LAST NAME</label>
                            <input className="form-control" id="employee_last_name" required value={user.employee_last_name} onChange={(e) => changeVal(e.currentTarget.id, e.currentTarget.value)}></input>
                            <label htmlFor='Username'>* USERNAME</label>
                            <input className="form-control" id="employee_username" required value={user.employee_username} onChange={(e) => changeVal(e.currentTarget.id, e.currentTarget.value)}></input>
                            <label htmlFor='UserPassword'>PASSWORD</label>
                            <input className="form-control" id="UserPassword" readOnly></input>
                            <label htmlFor='UserContactNo'>* CONTACT #</label>
                            <input className="form-control" id="employee_contact_no" required value={user.employee_contact_no} onChange={(e) => changeVal(e.currentTarget.id, e.currentTarget.value)}></input>
                            <label htmlFor='UserAddress'>STREET ADDRESS</label>
                            <input className="form-control" id="employee_street_address" value={user.employee_street_address} onChange={(e) => changeVal(e.currentTarget.id, e.currentTarget.value)}></input>
                            <label htmlFor='UserCity'>CITY</label>
                            <input className="form-control" id="employee_city" value={user.employee_city} onChange={(e) => changeVal(e.currentTarget.id, e.currentTarget.value)}></input>
                            <label htmlFor='UserState'>STATE</label>
                            <input className="form-control" id="employee_state" value={user.employee_state} onChange={(e) => changeVal(e.currentTarget.id, e.currentTarget.value)}></input>
                            <label htmlFor='UserZip'>ZIP CODE</label>
                            <input className="form-control" id="employee_zip_code" value={user.employee_zip_code} onChange={(e) => changeVal(e.currentTarget.id, e.currentTarget.value)}></input>
                            <label htmlFor='UserEmail'>EMAIL</label>
                            <input type="email" placeholder="example@gmail/yahoo.com" pattern=".+@(gmail|yahoo)\.com" className="form-control" id="employee_email" value={user.employee_email} onChange={(e) => changeVal(e.currentTarget.id, e.currentTarget.value)}></input>
                        </div>

                        
                            <div key={`default-checkbox`} className="mb-3" >
                                <Form.Check
                                    type={'checkbox'}
                                    onChange={() => {
                                        if (isAdmin === "false" && isDriver === "true"){ //If the checkbox is already checked, user is Admin. 
                                            setDriver("false");
                                            setAdmin("true");
                                        }
                                        else { //If the checkbox is already checked, user is Driver.
                                            setDriver("true");
                                            setAdmin("false");
                                        }}
                                    } 
                                    id={`default-checkbox`}
                                    label={`Is Driver`}  
                                />
                            </div>
                        
                        <button type="submit" className={"btn btn-primary"}>SAVE</button>
                        <button type="reset" className={"btn btn-primary"} onClick={() =>window.location.reload()}>BACK</button>
                    </form>
                </div>

            </> : <>

                <h1>{errMsg}</h1>
            </>}
        </React.Fragment>
    )
}

export default UserForm;

EDIT: With the comment suggestions, I changed the button's code to:

<button type="submit" className={"btn btn-primary"}>SAVE</button>

And the form's code to:

<form onSubmit={handleForm} className='employee-details' data-transport-order="form">

But the page is still refreshing 页面在单击提交按钮时刷新而不是提交表单。

Thank you for any help!!

英文:

I am having an issue with my react.js / bootstrap app where my new users form is not submitting. I originally used e.preventDefault(), but this caused my form to not validate, so I removed it. Now, my form validates, however, when I click my submit button, the page refreshes and the form is not actually submitted. Any help would be SO appreciated!!

import React from &#39;react&#39;;
import { useState } from &#39;react&#39;;
import axios from &#39;../../api/axios&#39;;
import Form from &#39;react-bootstrap/Form&#39;;
import UserList from &#39;./UserList&#39;;
function UserForm({ user, setUser }) {
const [errMsg, setErrMsg] = useState(&quot;&quot;);
const changeVal = async (key, value) =&gt; {
setUser(user =&gt; ({ ...user, [key]: value }));
}
/*Determines whether the user being created is an admin*/
let [isAdmin, setAdmin] = useState(&quot;true&quot;);
/*Determines whether the user being created is a driver*/
let [isDriver, setDriver] = useState(&quot;false&quot;);
const handleForm = async (e) =&gt; {
// e.preventDefault();
if (!user.employee_id) { //If the employee ID is blank, a new user is being added.
try {
const newUser = {
is_admin: isAdmin, is_driver: isDriver, employee_first_name: user.employee_first_name, employee_last_name: user.employee_last_name,
employee_username: user.employee_username, employee_contact_no: user.employee_contact_no, 
employee_street_address: user.employee_street_address, employee_password: &#39;testing123&#39;, employee_city: user.employee_city, employee_state: user.employee_state, employee_zip_code: user.employee_zip_code, 
employee_email: user.employee_email
};
let data = JSON.stringify(newUser);
console.log(data);
const response = await axios.post(&#39;/employee&#39;, data, {
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;
}
}
);
//fetchItem();
} catch (err) {
setErrMsg(JSON.stringify(err));
return;
}
} else {
try {
const newUser = {
employee_id: user.employee_id, is_admin: isAdmin, is_driver: isDriver, employee_first_name: user.employee_first_name, employee_last_name: user.employee_last_name,
employee_username: user.employee_username, employee_password: user.employee_password, employee_contact_no: user.employee_contact_no,
employee_street_address: user.employee_street_address,
employee_city: user.employee_city, employee_state: user.employee_state, employee_zip_code: user.employee_zip_code,
employee_email: user.employee_email
};
let data = JSON.stringify(newUser);
console.log(data);
const response = await axios.put(&#39;/employee&#39;, data, {
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;
}
}
);
//fetchItem();
} catch (err) {
setErrMsg(JSON.stringify(err));
return;
}
}
}
return (
&lt;React.Fragment&gt;
{!errMsg ? &lt;&gt; {
&lt;div className=&quot;form-container&quot;&gt;
&lt;div className=&#39;employee-id&#39;&gt;
&lt;label htmlFor=&#39;ID&#39;&gt;EMPLOYEE #&lt;/label&gt;
&lt;input className=&quot;form-control&quot; id=&quot;ID&quot; readOnly value={user.employee_id}&gt;&lt;/input&gt;
&lt;/div&gt;
&lt;form className=&#39;employee-details&#39; data-transport-order=&quot;form&quot;&gt;
&lt;div className=&#39;form-group&#39;&gt;
&lt;label htmlFor=&#39;UserFName&#39;&gt;* FIRST NAME&lt;/label&gt;
&lt;input type=&quot;text&quot; className=&quot;form-control&quot; id=&quot;employee_first_name&quot; required value={user.employee_first_name} onChange={(e) =&gt; changeVal(e.currentTarget.id, e.currentTarget.value)}&gt;&lt;/input&gt;
&lt;label htmlFor=&#39;UserLName&#39;&gt;* LAST NAME&lt;/label&gt;
&lt;input className=&quot;form-control&quot; id=&quot;employee_last_name&quot; required value={user.employee_last_name} onChange={(e) =&gt; changeVal(e.currentTarget.id, e.currentTarget.value)}&gt;&lt;/input&gt;
&lt;label htmlFor=&#39;Username&#39;&gt;* USERNAME&lt;/label&gt;
&lt;input className=&quot;form-control&quot; id=&quot;employee_username&quot; required value={user.employee_username} onChange={(e) =&gt; changeVal(e.currentTarget.id, e.currentTarget.value)}&gt;&lt;/input&gt;
&lt;label htmlFor=&#39;UserPassword&#39;&gt;PASSWORD&lt;/label&gt;
&lt;input className=&quot;form-control&quot; id=&quot;UserPassword&quot; readOnly&gt;&lt;/input&gt;
&lt;label htmlFor=&#39;UserContactNo&#39;&gt;* CONTACT #&lt;/label&gt;
&lt;input className=&quot;form-control&quot; id=&quot;employee_contact_no&quot; required value={user.employee_contact_no} onChange={(e) =&gt; changeVal(e.currentTarget.id, e.currentTarget.value)}&gt;&lt;/input&gt;
&lt;label htmlFor=&#39;UserAddress&#39;&gt; STREET ADDRESS&lt;/label&gt;
&lt;input className=&quot;form-control&quot; id=&quot;employee_street_address&quot; value={user.employee_street_address} onChange={(e) =&gt; changeVal(e.currentTarget.id, e.currentTarget.value)}&gt;&lt;/input&gt;
&lt;label htmlFor=&#39;UserCity&#39;&gt; CITY&lt;/label&gt;
&lt;input className=&quot;form-control&quot; id=&quot;employee_city&quot; value={user.employee_city} onChange={(e) =&gt; changeVal(e.currentTarget.id, e.currentTarget.value)}&gt;&lt;/input&gt;
&lt;label htmlFor=&#39;UserState&#39;&gt;STATE&lt;/label&gt;
&lt;input className=&quot;form-control&quot; id=&quot;employee_state&quot; value={user.employee_state} onChange={(e) =&gt; changeVal(e.currentTarget.id, e.currentTarget.value)}&gt;&lt;/input&gt;
&lt;label htmlFor=&#39;UserZip&#39;&gt;ZIP CODE&lt;/label&gt;
&lt;input className=&quot;form-control&quot; id=&quot;employee_zip_code&quot; value={user.employee_zip_code} onChange={(e) =&gt; changeVal(e.currentTarget.id, e.currentTarget.value)}&gt;&lt;/input&gt;
&lt;label htmlFor=&#39;UserEmail&#39;&gt;EMAIL&lt;/label&gt;
&lt;input type=&quot;email&quot; placeholder=&quot;example@gmail/yahoo.com&quot; pattern=&quot;.+@(gmail|yahoo)\.com&quot; className=&quot;form-control&quot; id=&quot;employee_email&quot; value={user.employee_email} onChange={(e) =&gt; changeVal(e.currentTarget.id, e.currentTarget.value)}&gt;&lt;/input&gt;
&lt;/div&gt;
{
&lt;div key={`default-checkbox`} className=&quot;mb-3&quot; &gt;
&lt;Form.Check
type={&#39;checkbox&#39;}
onChange={() =&gt; {
if (isAdmin === &quot;false&quot; &amp;&amp; isDriver === &quot;true&quot;){ //If the checkbox is already checked, user is Admin. 
setDriver(&quot;false&quot;);
setAdmin(&quot;true&quot;);
}
else { //If the checkbox is already checked, user is Driver.
setDriver(&quot;true&quot;);
setAdmin(&quot;false&quot;);
}}
} 
id={`default-checkbox`}
label={`Is Driver`}  
/&gt;
&lt;/div&gt;
}
&lt;button type=&quot;save&quot; className={&quot;btn btn-primary&quot;} onClick={(e) =&gt; handleForm(e)}&gt;SAVE&lt;/button&gt;
&lt;button type=&quot;reset&quot; className={&quot;btn btn-primary&quot;} onClick={() =&gt;window.location.reload()}&gt;BACK&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
}  &lt;/&gt; : &lt;&gt;
&lt;h1&gt;{errMsg}&lt;/h1&gt;
&lt;/&gt;}
&lt;/React.Fragment&gt;
)
}
export default UserForm;

EDIT: With the comment suggestions, I changed the button's code to:

&lt;button type=&quot;submit&quot; className={&quot;btn btn-primary&quot;}&gt;SAVE&lt;/button&gt;

And the form's code to:

&lt;form onSubmit = {handleForm} className=&#39;employee-details&#39; data-transport-order=&quot;form&quot;&gt;

But the page is still refreshing 页面在单击提交按钮时刷新而不是提交表单。

Thank you for any help!!

答案1

得分: 1

Sure, here are the translations for the code changes you provided:

change :

&lt;form className=&#39;employee-details&#39; data-transport-order=&quot;form&quot;&gt;

to :

&lt;form onSubmit={handleForm} className=&#39;employee-details&#39; data-transport-order=&quot;form&quot;&gt;

and change :

&lt;button type=&quot;save&quot; className={&quot;btn btn-primary&quot;} onClick={(e) =&gt; handleForm(e)}&gt;SAVE&lt;/button&gt;

to :

&lt;button type=&quot;submit&quot; className={&quot;btn btn-primary&quot;}&gt;SAVE&lt;/button&gt;
英文:

change :

 &lt;form className=&#39;employee-details&#39; data-transport-order=&quot;form&quot;&gt;

to :

 &lt;form onSubmit = {handleForm} className=&#39;employee-details&#39; data-transport-order=&quot;form&quot;&gt;

and change :

&lt;button type=&quot;save&quot; className={&quot;btn btn-primary&quot;} onClick={(e) =&gt; handleForm(e)}&gt;SAVE&lt;/button&gt;

to :

&lt;button type=&quot;submit&quot; className={&quot;btn btn-primary&quot;} &gt;SAVE&lt;/button&gt;

答案2

得分: 1

Sure, here's the translated code snippet:

将您的代码中以下部分更改为以下内容

<form className='employee-details' onSubmit={handleForm} data-transport-order="form">
    <button type="submit" className={"btn btn-primary"} >保存</button>
</form>

然后取消注释e.preventDefault()
英文:

Change following in your code to below

&lt;form className=&#39;employee-details&#39; onSubmit={handleForm} data-transport-order=&quot;form&quot;&gt;

&lt;button type=&quot;submit&quot; className={&quot;btn btn-primary&quot;} &gt;SAVE&lt;/button&gt;

Then uncomment e.preventDefault()

huangapple
  • 本文由 发表于 2023年5月7日 09:44:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定