动态添加表格行反应挂钩

时间:2020-06-05 09:36:44

标签: reactjs react-hooks

我有一个表,在其中映射了一些数据,在+按钮上,我想添加新表行并使用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 (

有人可以告诉我这是怎么回事,谢谢。

1 个答案:

答案 0 :(得分:1)

调查是一个具有数组问题的对象(我对吗?

您将使用 setSurvey 返回数组。

setSurvey((preSurvey) => {questions:[...preSurvey.questions, newState]})
相关问题