gpt4 book ai didi

javascript - 更新 React Js 中的对象数组

转载 作者:行者123 更新时间:2023-12-01 02:52:08 24 4
gpt4 key购买 nike

我想在 onChange 事件上更新问题名称。但问题是如果我只改变一个问题,每个问题都会改变。如何解决它?

class QuestionCreate extends React.Component {
constructor(props){
super(props);
this.state = {
datas: [],
default_question: {
isNew: true,
question: {
name: 'Click to write the question text',
answer_options: [
{name: 'click to write choice 1', 'choice': true},
{name: 'click to write choice 1', 'choice': true},
{name: 'click to write choice 1', 'choice': true},
]
}
}
}

}


onChangeQuestion(qustions, index, event){
let all_data = this.state.datas;
let currentQuestion = all_data[index].question
all_data[index]['question']['name'] = event.target.value;
console.log(all_data[index]['question']['name'])
this.setState({datas: all_data})

}

displayRow(){
let rowData = this.state.datas.map( (data, index) =>{
console.log("this is data:", data, index);
return(
<div className="well" key={ index }>
<h3>Q. <input type="text" onChange={ this.onChangeQuestion.bind(this, data, index) } value={ data.question.name } /></h3>
<ul>
<li>option</li>
</ul>
</div>
)
})

return rowData;
}

enter image description here

最佳答案

您正在直接改变您的状态。

let all_data = this.state.datas;
let currentQuestion = all_data[index].question
all_data[index]['question']['name'] = event.target.value;

用途:

let all_data = JSON.parse(JSON.stringify(this.state.datas));
let currentQuestion = all_data[index].question;
all_data[index]['question']['name'] = event.target.value;
this.setState({datas: all_data});

这些问题也可能有帮助。

关于javascript - 更新 React Js 中的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46902391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com