在React Js中更新对象数组

时间:2017-10-24 04:46:12

标签: javascript reactjs

我想在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

2 个答案:

答案 0 :(得分:2)

您正在直接改变您的州。

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});

这些问题也可能有所帮助。

答案 1 :(得分:0)

在编辑onChangeQuestion函数后正在运行。

onChangeQuestion(qustions, index, event){
    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});
}