我正在尝试开发我的第一个 React 应用程序。后端工作正常。无论如何,我不知道如何将反应表单中输入的数据插入到我的数据库中。我尝试使用 axios,但遇到了很多问题。这是我的代码: 后端:
router.post('/insert',(req,res) =>{
jsondata = req.body;
description = jsondata['description'];
distance = jsondata['distance'];
hours = jsondata['hours'];
minutes = jsondata['minutes'];
seconds = jsondata['seconds'];
conn.query('INSERT INTO run (description, distance, hours, minutes, seconds) VALUES (?,?,?,?,?)', [description,distance,hours,minutes,seconds], (err) =>{
if(err)
res.send(err)
if(!err)
res.send("Insert succeded.")
})
})
前端:
import React, {useEffect, useState} from 'react';
import {Link} from 'react-router-dom';
function Insert(){
return(
<div>
<form>
<p>Insert the details of your run</p>
<input type="text" id="description" placeholder="Insert a description of your run"></input>
<input type="text" id="description" placeholder="Insert a description of your run"></input>
<input type="number" id="description" placeholder="Insert the distance of your run"></input>
<input type="number" id="description" placeholder="Insert the hours of your run"></input>
<input type="number" id="description" placeholder="Insert the minutes of your run"></input>
<input type="number" id="description" placeholder="Insert the seconds of your run"></input>
<button id="btn">Submit</button>
</form>
</div>
);
}
export default Insert;
非常感谢您的帮助!
在输入上,您需要放置方法来处理其更改,您可以将值存储在 useState 中,例如:
const [name, setName] = useState('');
...
<input type="text" value={name} onChange={setName} />
然后,通过添加这样的方法调用来处理提交表单
<form onSubmit={handleOnSubmit}>
您将在其中收集输入数据并使用 axios 发送它,例如:
handleOnSubmit(e) {
e.preventDefault()
const data = {
name: name
// other fields...
}
axios.post('http://your-url.com', data)
.then((res) => {
console.log(res.data)
}).catch((error) => {
console.log(error)
});
}
另外,即使这已经晚了很多年了......(!)
id="description" 在表单中应该是唯一的,否则如何引用它?