【发布时间】:2021-05-17 21:47:34
【问题描述】:
我正在创建一个注册表单以响应验证。我要问的值是用户名、电子邮件、密码+(控制密码)。有关表单的所有内容、验证、错误,如果您单击注册,您将进入一个新页面。现在我想将值提取到我的 MySql 数据库中。我成功地将内容放入我的数据库中,因此链接有效,但我无法获取我在表单中输入的值。
我试过了
onChange={(e) => {
setUsernameReg(e.target.value);
}}
(see commented item)
但是当我尝试这个时,我无法在用户名中填写任何内容。除名称外,其他输入(电子邮件、密码)的代码相同。
简而言之,我想将您在文本框中输入的值获取到我的数据库中。
代码:FormSignup.js
import React, { useEffect, useState } from 'react';
import Axios from 'axios';
import validate from './validateInfo';
import useForm from './useForm';
import './Form.css';
const FormSignup = ({ submitForm }) => {
const { handleChange, handleSubmit, values, errors } = useForm(
submitForm,
validate
);
const [usernameReg, setUsernameReg] = useState("");
const [emailReg, setEmailReg] = useState("");
const [passwordReg, setPasswordReg] = useState("");
Axios.defaults.withCredentials = true;
const register = () => {
Axios.post("http://localhost:3001/register", {
username: usernameReg,
password: passwordReg,
email: emailReg,
}).then((response) => {
console.log(response);
});
};
return (
<div className='form-content-right'>
<form onSubmit={handleSubmit} className='form' noValidate>
<h1>
Get started with us today! Create your account by filling out the
information below.
</h1>
<div className='form-inputs'>
<label className='form-label'>Username</label>
<input
className='form-input'
type='text'
name='username'
placeholder='Enter your username'
value={values.username}
onChange={handleChange}
/*
//onChange={(e) => {
// setUsernameReg(e.target.value);
//}}
*/
/>
代码 UseForm.js
import { useState, useEffect } from 'react';
import Axios from 'axios';
const useForm = (callback, validate) => {
const [values, setValues] = useState({
username: '',
email: '',
password: '',
password2: ''
});
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [usernameReg, setUsernameReg] = useState("");
const [emailReg, setEmailReg] = useState("");
const [passwordReg, setPasswordReg] = useState("");
Axios.defaults.withCredentials = true;
const register = () => {
Axios.post("http://localhost:3001/register", {
username: usernameReg,
password: passwordReg,
email: emailReg,
}).then((response) => {
console.log(response);
});
};
const handleChange = e => {
const { name, value } = e.target;
setValues({
...values,
[name]: value
});
};
const handleSubmit = e => {
e.preventDefault();
setErrors(validate(values));
setIsSubmitting(true);
};
useEffect(
() => {
if (Object.keys(errors).length === 0 && isSubmitting) {
callback();
}
},
[errors]
);
return { handleChange, handleSubmit, values, errors };
};
导出默认useForm; 代码来自https://www.youtube.com/watch?v=KGFG-yQD7Dw&t和https://www.youtube.com/watch?v=W-sZo6Gtx_E&t
【问题讨论】:
标签: javascript mysql reactjs forms axios