如何解决如何将输入数据存储到数组的选项中?
这是我的 react 和 nodejs 代码,我想在其中使用 react 表单创建民意调查,但我不明白我的代码出了什么问题...!`这里我有 4 个输入字段,带有 { option1: "",option2 :"",option3: "",option4: "" },但是我不知道如何存储数据,就像我使用POSTMAN存储数据一样......!任何人都可以帮助请帮助....! 反应 JS 代码 --->
import React,{ useState,useEffect } from "react";
import "../styles.css";
import { isAutheticated } from "../auth/helper/index";
import { createaPoll } from "./helper/adminapicall";
const AddPoll = () => {
const { user,token } = isAutheticated();
const [value,setValue] = useState({
question: "",options: { option1: "",option2: "",option4: "" },error: "",loading: "false",getRedirect: false,formData: "",});
const { question,options,error,loading,getRedirect,formData } = value;
const handleChange = (event) => {
// setError("");
setValue({ ...value,[event.target.name]: event.target.value });
// console.log(event.target.value);
const newOption = {
...value.options,[event.target.name]: event.target.value,};
setValue((prev) => ({ ...prev,options: newOption }));
};
const onSubmit = (event) => {
event.preventDefault();
setValue({ ...value,loading: true });
// console.log(handel);
const { option1,option2,option3,option4 } = options;
const newOptions = [option1,option4];
createaPoll(user._id,token,{ question,options: newOptions }).then(
(data) => {
console.log(data);
if (data.error) {
setValue({ ...value,error: data.error });
} else {
setValue({
...value,question: "",});
}
}
);
};
return (
<div className="AddPoll">
<div className="container">
<h1>Add New Poll</h1>
<form>
<textarea
rows="4"
cols="50"
className="form-control mb-2"
placeholder="Question"
name="question"
value={question}
onChange={(event) => handleChange(event)}
autoFocus
></textarea>
<input
type="text"
className="form-control mb-2"
placeholder="Option1"
onChange={(event) => handleChange(event)}
name="option1"
value={options.option1}
/>
<input
type="text"
className="form-control mb-2"
placeholder="Option2"
onChange={(event) => handleChange(event)}
name="option2"
value={options.option2}
/>
<input
type="text"
className="form-control mb-2"
placeholder="Option3"
onChange={(event) => handleChange(event)}
name="option3"
value={options.option3}
/>
<input
type="text"
className="form-control mb-2"
placeholder="Option4"
onChange={(event) => handleChange(event)}
name="option4"
value={options.option4}
/>
<button type="submit" onClick={onSubmit} className="btn Submitbtn">
Submit
</button>
</form>
</div>
</div>
);
};
export default AddPoll;
节点代码--->
exports.createPolls = async (req,res,next) => {
try {
const { question,options } = req.body;
const dynamic = {};
options.forEach((opt) => {
dynamic[opt.toLowerCase()] = [];
});
const polls = await Poll.create({
question,options: dynamic,});
polls.save((err,polls) => {
if (err) {
res.status(400).json({
error: "Saving Poll in DB failed",});
}
res.json(polls);
});
} catch (error) {
error.status = 400;
next(error);
}
};
当我使用 POSTMAN 时,它工作正常!这是我的邮递员图片
每当我使用反应表单单击提交按钮时,反应表单上都会出现错误(未处理的拒绝(类型错误):无法读取未定义的属性“错误”)在行号 - 39
当我检查我的节点服务器时,它也显示了一个错误(无法读取 undefined 的属性 'forEach' ) 我不明白为什么会这样......!因为 POSTMAn 可以很好地处理此代码,但不会对表单做出反应,,,!请帮助...!
解决方法
options 必须是一个数组才能使用 forEach 方法对其进行迭代
,错误响应需要放在 catch() 块中的 then() 块之后。您可以使用 err.response.data.error 定位 err 响应数据以获取您的消息。这样任何 response.status !== 200 都可以有自己的语句。
import csv
with open ('anscombe.csv','r') as datafile:
csv_reader = csv.reader(datafile)
for line in csv_reader:
print(line)
如果选项只是字符串,只需将它们放入一个数组中,然后像这样将它们传递到您的 req 对象中:
const onSubmit = (event) => {
event.preventDefault();
setValue({ ...value,error: "",loading: true });
// console.log(handel);
const { option1,option2,option3,option4 } = options;
const newOptions = [option1,option4];
createaPoll(user._id,token,{ question,newOptions }).then( //like this
(data) => {
setValue({
...value,question: "",options: { option1: "",option2: "",option3: "",option4: "" },loading: "false",getRedirect: false,formData: "",}).catch((err) => {
console.log(err.response.data.error)
setValue({ ...value,error: err.response.data.error });
});
}
}
);
};
然后在你的路由中控制台.log你的newOptions数组和req.body,看看你的数据是否被正确定向,
exports.createPolls = async (req,res,next) => {
try {
const { question,options } = req.body;
console.log(question,options,req.body) // what does this look like?
const dynamic = {};
options.forEach((opt) => {
dynamic[opt.toLowerCase()] = [];
});
const polls = await Poll.create({
question,options: dynamic,});
polls.save((err,polls) => {
if (err) {
res.status(400).json({
error: "Saving Poll in DB failed",});
}
res.json(polls);
});
} catch (error) {
error.status = 400;
next(error);
}
};
也许数据没有被传递到路由属性?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。