如何在对象数组的数组中添加元素



我收到错误:this.state.questions[key] is not iterable
我想将optiontext从输入字段推送到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] });
}

提取选项并附加一个值。 在使用合并选项拼接新问题之前克隆问题。 更新状态。

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>

最新更新