Javascript 如何使用React中的useState在对象数组中添加对象?
我正在编写一个包含问题、答案和分数/成绩的测试页面。根据管理员选择的问题数量,它将生成与问题、答案和点对应的动态输入字段,并带有添加问题按钮。当我按下add question时,应该有一个对handleQuestion函数的回调,其中创建了一个带有question、answer和points属性的对象。 使用useState设置问题、答案和分数的值。我尝试使用扩展运算符(…)在testContent数组中添加新对象,但在完成问题字段后按“添加”时,没有任何更改。有人能告诉我我做错了什么吗 这是handleQuestion func:Javascript 如何使用React中的useState在对象数组中添加对象?,javascript,json,reactjs,react-hooks,Javascript,Json,Reactjs,React Hooks,我正在编写一个包含问题、答案和分数/成绩的测试页面。根据管理员选择的问题数量,它将生成与问题、答案和点对应的动态输入字段,并带有添加问题按钮。当我按下add question时,应该有一个对handleQuestion函数的回调,其中创建了一个带有question、answer和points属性的对象。 使用useState设置问题、答案和分数的值。我尝试使用扩展运算符(…)在testContent数组中添加新对象,但在完成问题字段后按“添加”时,没有任何更改。有人能告诉我我做错了什么吗 这是h
const handleQuestion = (e) => {
e.preventDefault();
const createQuestion= {
"questionContent": question,
"questionAnswer": answer,
"questionPoints": points
}
setTestContent(testContent => [...testContent, createQuestion]);
}
这是问题、答案和要点的设定位置:
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>
))
内容不是createQuestion上的键,因此您将只向testContent添加未定义的内容。createQuestion只有“questionContent”、“questionAnswer”和“questionPoints”作为键 你想做什么
setTestContent(testContent => [...testContent, createQuestion]);
相反我想在testContent数组中添加createQuestion对象,然后您可以执行setTestContent(testContent=>[…testContent,createQuestion]);我试过了,如果我点击一次按钮,它不会做出任何改变,如果我点击两次,它会将我的对象放入该数组中。但例如,当我完成第二个问题的字段并按Add时,它会再次添加上一个对象,第二次按Add时,它会放置第二个对象。
const createQuestion= {
"questionContent": question,
"questionAnswer": answer,
"questionPoints": points
}
setTestContent(testContent => [...testContent, createQuestion]);