Saya mendapatkan kesalahan: this.state.questions[key] is not iterable
Saya ingin mendorong optiontext dari bidang input ke array options

this.state = {
  sections: [{
    key: 1,
    value: 1
  }],
  optionText: '',
  questions: [{
    id: Math.round(Math.random() * 1000000000000000),
    query: '',
    sectionId: 1,
    selectedType: 1,
    options: ['1st option', ],
    isChecked: true
  }],
}
addOption = (key) => {
  const addtext = this.state.optionText //typed text in input 
  let option = this.state.questions[key].options; //trying to access array in array of object 
  this.setState({
    questions: [...this.state.questions[key], addtext]
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
  sections: [{ key: 1, value: 1 }],
  optionText: '',
      surveyTitle: '',
      description: '',
      questions: [{
        id: Math.round(Math.random() * 1000000000000000),
        query: '',
        sectionId: 1,
        selectedType: 1,
        options: ['1st option',],
        isChecked: true
      }],
    }
 addOption = (key) => {
    const addtext = this.state.optionText //typed text in input 
    let option = this.state.questions[key].options; //trying to access array in array of object 
    this.setState({ questions: [...this.state.questions[key], addtext] });
  }
-1
Tarang Jain 3 Juli 2020, 14:17

1 menjawab

Jawaban Terbaik

Ekstrak opsi dan tambahkan nilai. Pertanyaan klon sebelum penyambungan pertanyaan baru dengan opsi gabungan. Perbarui status.

this.state = {
  sections: [{
    key: 1,
    value: 1
  }],
  optionText: '',
  questions: [{
    id: Math.round(Math.random() * 1000000000000000),
    query: '',
    sectionId: 1,
    selectedType: 1,
    options: ['1st option', ],
    isChecked: true
  }],
}
addOption = (key) => {
  const addtext = this.state.optionText //typed text in input 
  let options = this.state.questions[key].options; //trying to access array in array of object 
  options = [...options, addText];
  const questions = [...this.state.questions];
  questions.splice(key, 1, {...questions[key], options});

  this.setState({
    questions
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
0
user120242 3 Juli 2020, 11:48