[英]How to add an object in an array of objects using useState in React?
I am working on a page that contains a test with questions, answers and points/grades.我正在处理一个包含问题、答案和分数/等级的测试的页面。 Based on the number of questions selected by admin, it will generate a dynamic inputs fields corresponding to the question, answer and point, with an add question button.
根据管理员选择的问题数量,它会生成一个与问题、答案和分数对应的动态输入字段,并带有一个添加问题按钮。 When I press the add question there should be a callback to the handleQuestion function where an object is created with question, answer and points properties.
当我按下添加问题时,应该有一个对 handleQuestion function 的回调,其中 object 使用问题、答案和点属性创建。 The values for question, answer and points are set using useState.
问题、答案和分数的值是使用 useState 设置的。 I try to add the new object in testContent array using spread operator (...), but when I press "add" after I completed the fields for a question, nothing changes.
我尝试使用扩展运算符 (...) 在 testContent 数组中添加新的 object,但是当我在完成问题字段后按“添加”时,没有任何变化。 Can somebody give me an idea on what I am doing wrong?
有人可以告诉我我做错了什么吗?
This is the handleQuestion func:这是 handleQuestion 函数:
const handleQuestion = (e) => {
e.preventDefault();
const createQuestion= {
"questionContent": question,
"questionAnswer": answer,
"questionPoints": points
}
setTestContent(testContent => [...testContent, createQuestion]);
}
This is where the question, answer and points are setted:这是设置问题、答案和分数的地方:
return questions.map((quest) => (
<div>
<div>
<label htmlFor="testContent"> Question {quest + 1} </label>
<input
type="text"
className="form-control"
name="question"
//value={question}
onChange={onChangeQuestion}
validations={[required, validContent]}
/>
</div>
<div>
<label htmlFor="testContent"> Answer for question {quest + 1}</label>
<input
type="text"
className="form-control"
name="answer"
//value={question}
onChange={onChangeAnswer}
validations={[required, validContent]}
/>
</div>
<div>
<label htmlFor="testContent"> Points for question {quest + 1}</label>
<input
type="text"
className="form-control"
name="points"
// value={}
onChange={onChangePoints}
validations={[required, validContent]}
/>
</div>
<button onClick={handleQuestion}>Add question</button>
</div>
))
And:和:
const[question, setQuestion] = useState("");
const[answer, setAnswer] = useState("");
const[points, setPoints] = useState("");
const[testContent, setTestContent] = useState([]);
content is not a key on createQuestion, so you will only add undefined to the testContent. content 不是 createQuestion 的键,因此您只会将 undefined 添加到 testContent。 createQuestion only has "questionContent", "questionAnswer" and "questionPoints" as keys
createQuestion 只有“questionContent”、“questionAnswer”和“questionPoints”作为键
const createQuestion= {
"questionContent": question,
"questionAnswer": answer,
"questionPoints": points
}
prob you want to do你想做的问题
setTestContent(testContent => [...testContent, createQuestion]);
instead反而
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.