[英]Add object to end of array react
在我的 Next.JS 應用程序中構建 object 時遇到了一點問題。 這很可能是因為我缺乏 JavaScript 和 React 能力。 我有一個從 api 調用呈現的表單。 它返回一個對象數組,如下所示:
[
{
"formId": "uuid",
"description": "Description of form",
"questions": [
{
"questionId": "uuid",
"text": "question 1?",
"alternatives": [
{
"text": "No",
"ratingValue": 1
},
{
"text": "Yes",
"ratingValue": 5
}
]
}
]
}]
object 將包含多個 forms 並且每個表單可以包含多個問題。 我將每個問題的值傳遞到我的組件中名為 pushAnswer 的 function 中,如下所示:
<Form.Check
type="radio"
name={question.questionId}
value={alternative.ratingValue}
onChange={event => {
pushAnswer(form.formId, question.questionId, event.target.value)
}} />
我有 state 變量const [formBody, setFormBody] = useState({form:[]})
而pushAnswer
function 看起來像這樣:
const pushAnswer = (formId, questionId, answerValue) => {
const currentForm = formBody;
let answeredForm = currentForm.forms.find(form => form.formId === formId);
// if the form ID doesn't exist, add it
if (!answeredForm) {
answeredForm = {
formId,
answers: []
}
}
// check if the questionId exists
let answeredQuestion = answeredForm.answers.find(answer => answer.questionId === questionId)
if (!answeredQuestion) {
answeredQuestion = {
questionId,
rating: answerValue
}
}
answeredQuestion.rating = answerValue;
setFormBody(oldForm => ({
...oldForm,
forms: [
{
formId: answeredForm.formId,
questions: [
{
questionId: answeredQuestion.questionId,
rating: answeredQuestion.rating
}
]
}
]
}))
}
我想產生這樣的答案:
{
"forms": [
{
"formId": "2b945644-a9c3-473e-afac-1236bc1575ce",
"questions": [
{
"questionId": "289a9e8a-a607-464a-8939-48223819f413",
"rating": "1"
},
{
"questionId": "another uuid",
"rating": "5"
}
]
},
{
"formId": "another uuid",
"questions": [
{
"questionId": "another uuid",
"rating": "5"
}
]
}
]
}
第一個問題被添加到 formBody 中,但是當我嘗試獲取另一個問題的值時,我在let answeredQuestion = answeredForm.answers.find(answer => answer.questionId === questionId)
收到一個錯誤,上面寫着Cannot read property 'find' of undefined
。
誰能建議我如何解決這個問題?
您沒有在 state 中保存正確的值,它應該是
const [formBody, setFormBody] = useState({forms:[]})
setFormBody(oldForm => ({forms: [
...oldForm.forms,
[
{
formId: answeredForm.formId,
questions: [
{
questionId: answeredQuestion.questionId,
rating: answeredQuestion.rating
}
]
}
]
]}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.