【发布时间】:2021-09-10 10:24:54
【问题描述】:
我为我的应用程序制作了一个表单和一个表格,因此如果我输入数据并提交它必须为自己创建一个单独的行。它有效,但在提交我的表单后,它给了我这条路线
只有当我刷新页面时,它才会在表格中形成一行
这是处理我的表单提交的函数
const handleSubmit = () => {
setMessage("");
setLoading(true);
form.current.validateAll();
if (checkBtn.current.context._errors.length === 0) {
ProductService.addProduct(id, barcode, productName, price, quantity).then(
(response, ) => {
setMessage(response.data.message);
setSuccessful(true);
},
(error) => {
const resMessage =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
setMessage(resMessage);
setSuccessful(false);
}
);
}
};
此函数获取数据并更新我的表的状态
const InventoryTable = () => {
const [data, setData] = useState([]);
const fetchData = () => {
return fetch("http://localhost:8080/api/inventory/getProductData")
.then((response) => response.json())
.then((details) => setData(details));}
useEffect(() => {
fetchData();
}, []);
ProductService.addProduct() 是来自服务文件的函数,用于将数据发送到 API 路由,其代码如下所示
const addProduct = (id, barcode, productName, price, quantity) => {
return axios.post(API_URL + "addProduct" , {
username,
id,
barcode,
productName,
price,
quantity,
});
};
并且发送到的 API 路由具有回调的控制器函数,该函数将产品保存到 MONGOdB 中
const addProduct = (req, res) => {
User.findOne({
username: req.body.username
}, function(err, user) {
if (err) {
res.status(500).send({ message: err })
}else{
user.store.push({
id: req.body.id,
barcode: req.body.barcode,
productName : req.body.productName,
price : req.body.price,
quantity: req.body.quantity
})
user.save(function(err, newUser) {
if (err) {
res.status(500).send({ message: err });
} else {
console.log(newUser);
res.status(200).send({ message: "Product updated successfully!!"})
}
})
}
})
};
当我使用event.preventaDefault(); 时,我必须刷新两次以确保数据呈现
如果你们需要其他什么来解决问题,请告诉我
我应该怎么做才能解决这个问题?
这是与 react-router 反应,后端与 nodejs 和数据库是 mongodb
提前致谢
【问题讨论】:
-
你能添加一个Minimal, Complete, and Reproducible Code Example 的相关代码你有问题吗?通常这意味着您正在使用陈旧的状态和/或道具。
-
你能展示渲染和处理表单的组件的代码吗?
-
如果不查看您的代码,就无法确定您的问题。为了让其他人帮助您,您还需要发布您的代码。但是听起来好像在提交表单时没有更新状态,因此不会重新渲染组件。
-
@DrewReese 感谢您的快速回复。我已经用代码编辑了我的问题。
-
ProductService.addProduct是添加一行数据的那块吗?是什么给了你这条路线?路由与代码sn-p的相关性是什么?
标签: node.js reactjs mongodb routes react-router