>我有一个表,我将一些数据映射到其中,+
按钮上我想添加新的表行并使用 react hook 为该表行设置新defaultState
import React, { useState, useEffect } from 'react'
import { useMutation, useQuery } from '@apollo/react-hooks'
import { Link, useParams } from 'react-router-dom'
import './style.css'
import {
GET_SURVEY,
CREATE_SURVEY,
} from './queries'
import { pushError } from '../../modules/error'
export default function SurveyDetails() {
const params = useParams()
const { data } = useQuery(GET_SURVEY, { variables: { id: params.surveyId } })
const [survey, setSurvey] = useState({})
useEffect(() => {
async function loadSurvey() {
if (data && data.me.survey) {
await setSurvey(data.me.survey)
}
}
loadSurvey()
}, [data])
const HomePage = () => (
<Link to="/home">Home</Link>
)
const SurveyPage = () => (
<Link to="/survey">Survey</Link>
)
const hadnleAddRow = () => {
console.log('?????')
const questionId = (survey.questions || []).map((t) => t.id)
const newState = {
id: params.surveyId,
questions: {
id: questionId,
questionText: '',
type: '',
options: [],
}
}
// console.log(setSurvey((preSurvey) => [...preSurvey, {}]))
setSurvey((preSurvey) => [...preSurvey, newState])
}
return (
<div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<h2>Survey Details</h2>
<div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', flex: '1' }}>
<span style={{ paddingRight: '25px' }}><SurveyPage /></span>
<span><HomePage /></span>
</div>
</div>
<table>
<tr>
<th>Question Text</th>
<th>Type</th>
<th>Options</th>
<th>Status</th>
<th>Edit</th>
<th><button type="submit" onClick={hadnleAddRow}>+</button></th>
<th>Remove</th>
</tr>
{(survey.questions || []).map((q) => (
<tr key={q.id}>
<td>{ q.questionText }</td>
<td>{ q.type }</td>
<td>
{ q.options.join(', ')}
{' '}
</td>
<td>{ survey.status }</td>
<td><button type="submit" onClick={openModal}>Edit</button></td>
<td />
<td><button type="submit">-</button></td>
</tr>
))}
</table>
</div>
)
}
现在我面临的错误是这个
TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
81 | }
82 | }
83 | // console.log(setSurvey((preSurvey) => [...preSurvey, {}]))
> 84 | setSurvey((preSurvey) => [...preSurvey, newState])
| ^ 85 | }
86 |
87 | return (
有人可以向我解释一下这里发生了什么,谢谢。
调查是一个对象,以数组的形式存在问题(我说得对吗?
您正在使用setSurvey返回数组。
setSurvey((preSurvey) => {questions:[...preSurvey.questions, newState]})