Получение значений полей формы React для отправки

Учитывая форму React, у меня возникают проблемы с получением значения из выбранного переключателя и текстового поля, если выбрано other. Я должен быть в состоянии передать поля в send() для сообщения, но не знаю, как их захватить.

class CancelSurvey extends React.Component {
constructor (props) {
  super(props)
  this.state = {
    reasons: [],
    reason: {}
  }
  this.processData = this.processData.bind(this)
  this.handleSubmit = this.handleSubmit.bind(this)
  this.otherSelected = this.state.reason === "otheroption";
}

componentDidMount () {
  this.fetchContent(this.processData)
}

/**
 * Fetch reasons
 */

fetchContent (cb) {
  superagent
    .get('/api/user/survey')
    .then(cb)
}

/**
 * Set state after reasons have been fetched
 * @param data
 */

processData (data) {
  this.setState({
    reasons: data.body
  })
}

handleSubmit (e) {
  e.preventDefault()
  let reason = this.state.reason
  if (reason === 'otheroption') {
    reason = this.state.otherreason
  }
  console.log(reason)
  superagent
    .post('/api/user/survey')
    .send({
      optionId: this.state.reason.reason_id,
      optionText: this.state.reason.client_reason,
      otherReasonText: this.state.otherreason
    })
    .then(function (res) {
      console.log('Survey Sent!')
    })
}
  /**
   * render
   */
  render (props) {
    const content = this.props.config.contentStrings
    const reason = this.state.reasons.map((reason, i) => {
      return (
        <div className='fieldset__item' key={i}>
          <label>{reason.client_reason}</label>
          <input type='radio'
            id={reason.reason_id}
            value={reason.client_reason}
            name='reason'
            checked={this.state.reason.reason_id === reason.reason_id}
            onChange={() => this.setState({reason})} />
        </div>
      )
    })

    return (
      <div className='survey'>
        <h2 className='heading md'>{content.memberCancel.exitSurvey.heading}</h2>
        <p className='subpara'>{content.memberCancel.exitSurvey.subHeading}</p>
        <form id='exit-survey' onSubmit={this.handleSubmit}>
          <fieldset className='fieldset'>
            { reason }
            <label>Other reason not included above:</label>
            <input type='radio'
              id='otheroption'
              name='reason'
              value={this.state.reason.otherreason}
              onChange={() => this.setState({reason:{reason_id: 70, client_reason: 'other'}})} />
            <input className='valid'
              type='text'
              id='otheroption'
              name='othertext'
              placeholder={content.memberCancel.exitSurvey.reasonPlaceholder}
              onChange={(event) => this.setState({otherreason: event.target.value})} />
          </fieldset>
          <div className='footer-links'>
            <button className='btn btn--primary btn--lg' onClick={this.handleSubmit}>{content.memberCancel.exitSurvey.button}</button>
          </div>
        </form>
      </div>
    )
  }
}

export default CancelSurvey

person Matt    schedule 26.04.2018    source источник
comment
Вы не обновляете состояние, когда пользователь нажимает переключатель. Код, который я предоставил на ваш предыдущий вопрос здесь, показывает, что вам нужно использовать состояние для обработки значений формы.   -  person Will    schedule 26.04.2018
comment
@Will - Эта проблема / вопрос немного отличается. Вместо того, чтобы передавать поля формы другому компоненту, мне нужно получить значения и отправить их в функцию send. Я обновил свой код, но он не извлекает поля формы для передаваемых значений.   -  person Matt    schedule 26.04.2018
comment
Отправляет ли он какие-либо значения вместо них? Вы пытались объявить их в состоянии с тестовыми значениями?   -  person Will    schedule 26.04.2018
comment
Я понял, что отправляю неправильные значения полей для предопределенных параметров, но не могу понять, как получить и отправить параметр other.   -  person Matt    schedule 26.04.2018
comment
Как я уже говорил, вам нужно обрабатывать значения с состоянием, ваши вводы, которые сопоставляются, верны, но вы не делаете то же самое для статических после {причина}   -  person Will    schedule 26.04.2018


Ответы (1)


Ваши переменные неверны. Я обновил их до того, что считаю правильным.

handleSubmit (e) {
  e.preventDefault()
  superagent
    .post('/api/user/survey')
    .send({
      optionId: this.state.reason.reason_id,
      optionText: this.state.reason.client_reason,
      otherReasonText: this.state.reason.otherreason
    })
    .then(function (res) {
      console.log('Survey Sent!')
    })
    .catch(function (err) {
      console.log('Survey submission went wrong...')
    })
}
/**
 * render
 */
render (props) {
    const content = this.props.config.contentStrings
    const reason = this.state.reasons.map((reason, i) => {
        return (
            <div className='fieldset__item' key={i}>
                <label>{reason.client_reason}</label>
                <input 
                    type='radio'
                    id={reason.reason_id}
                    name='reason'
                    checked={this.state.reason.reason_id === reason.reason_id}
                    value={reason.client_reason}
                    onChange={() => this.setState({reason})} />
            </div>
        )
    })

    return (
        <div className='survey'>
            <h2 className='heading md'>{content.memberCancel.exitSurvey.heading}</h2>
            <p className='subpara'>{content.memberCancel.exitSurvey.subHeading}</p>
            <form id='exit-survey' onSubmit={this.handleSubmit}>
                <fieldset className='fieldset'>
                    { reason }
                    <label>Other reason not included above:</label>
                    <input type='radio'
                        id='otheroption'
                        name='otheroption'
                        value={this.state.reason.otherreason}
                        checked={this.state.reason.reason_id === 0}
                        onChange={() => this.setState({ reason: {reason_id: 0, client_reason: ""} })} />
                    <input className='valid'
                        type='text'
                        id='othertext'
                        name='othertext'
                        value={this.state.reason.otherreason}
                        placeholder={content.memberCancel.exitSurvey.reasonPlaceholder}
                        onChange={(event) => this.setState({ reason: {reason_id: 0, client_reason: "", otherreason: event.target.value} })} />
                </fieldset>
                <div className='footer-links'>
                    <button className='btn btn--primary btn--lg' onClick={this.handleSubmit}>{content.memberCancel.exitSurvey.button}</button>
                </div>
            </form>
        </div>
    );
}
person Will    schedule 26.04.2018
comment
Я обновил свой код в соответствии с вашим предложением, но получил неопределенность при отправке при выборе переключателя other. - person Matt; 26.04.2018
comment
Радиовход для other, когда он выбран, выходит из системы как undefined. Ввод текста выходит из системы, но также не отправляется. - person Matt; 26.04.2018
comment
Хм, установка значения ввода текста делает его неизменяемым. - person Matt; 26.04.2018
comment
Спасибо, что продолжаете помогать. С этим обновлением значения текстового ввода оно изменяется с неконтролируемого на контролируемый ввод Warning: A component is changing an uncontrolled input of type text to be controlled. - person Matt; 26.04.2018
comment
К сожалению нет. Он по-прежнему не использует ввод текста для otherReasonText: this.state.reason.otherreason в send() - person Matt; 26.04.2018
comment
Обновил мой код новым значением, но он по-прежнему отображается как неопределенное как для переключателя, так и для ввода текста по другой причине. Я думаю, что проблема может заключаться в том, что у меня не установлены идентификатор и причина для 'other', но не уверен. Любые дальнейшие идеи? Спасибо! - person Matt; 27.04.2018
comment
Это был шаг в правильном направлении, просто нужно было немного изменить. Я отмечу это как ответ и опубликую полную версию в своем вопросе. - person Matt; 27.04.2018
comment
Спасибо за вашу помощь! - person Matt; 27.04.2018