首页 > 解决方案 > 由于未连接表单而取消表单提交 - 控制台错误

问题描述

我在网上搜索过,但仍然找不到为什么我的表单没有提交,但它显示了前端的数据。我正在使用钩子从表单中获取数据。有没有办法获得更好或更简洁的代码行?TIA

这是我收到的控制台错误=>表单提交被取消,因为表单未连接

这是我的 AddUser.js

import {Form,FormGroup,Label,Input,Button} from 'reactstrap';
import{GlobalContext} from '../context/GlobalState';
import {Link, useHistory} from 'react-router-dom';
import {v4 as uuid} from 'uuid';


export const AddUser = () => {

  const {addEmployee } = useContext(GlobalContext);
  const [name, setName] = useState('');
  const [nameL,setNameL] = useState('');
  const [email,setEmail] = useState('');
  const [contact,setContact] = useState('');
  const [address,setAddress] = useState('');
  const [date,setDate] = useState('');

  const history= useHistory();

  const onChange = (e) =>{
      setName(e.target.value);
 
  }
  const onNameL = (e) =>{
 
      setNameL(e.target.value);
     
  }
  const onEmail = (e) =>{
      setEmail(e.target.value);
 
  }
  const onContact = (e) =>{
      setContact(e.target.value);
 
  }
  const onAddress = (e) =>{
      setAddress(e.target.value);
 
  }
  const onDate = (e) =>{
      setDate(e.target.value);
 
  }
  const onSubmit= () =>{
      
      const newEmployee = {
          id: uuid(),
          name,nameL,email,contact,address,date
      }
      
      addEmployee(newEmployee);
      
      history.push('/');

  }

  return (
      <React.Fragment>
          <Form onSubmit={onSubmit}>
              <FormGroup >
                  
                  <Label>First Name:</Label>
                  <Input type="text" value= {name}  onChange={onChange} placeholder="enter your First name"></Input>
                  <Label>Last Name:</Label>
                  <Input type="text"value= {nameL}  onChange={onNameL} placeholder="enter your Last name"></Input>
                  <Label>Email:</Label>
                  <Input type="email"value= {email}  onChange={onEmail} placeholder="Email Address"></Input>
                  <Label>Contact Number:</Label>
                  <Input type="number"value= {contact}  onChange={onContact} placeholder="Contact"></Input>
                  <Label>Address:</Label>
                  <Input type="text"value= {address}  onChange={onAddress} placeholder="enter your Address"></Input>
                  <Label>Enter Date of Employment:</Label>
                  <Input type="date"value= {date}  onChange={onDate} placeholder="enter date employed"></Input>
              </FormGroup>
              <Button type="submit" className="btn btn-success">Submit</Button>
              <Link to="/" className="btn btn-danger">Cancel</Link>
          </Form>
      </React.Fragment>
  )
}
export default AddUser`` 





标签: reactjsreact-hooksuse-state

解决方案


我只是将按钮类型更改为按钮而不是提交,它可以工作

<Button type="button" onClick={onSubmit} className="btn btn-success">Submit</Button>


推荐阅读