开发者问题收集

在 React Js 中更新对象数组

2017-10-24
243

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

在此处输入图片描述

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

这些问题也可能有帮助。

anand
2017-10-24

编辑 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});
}
Shaon shaonty
2017-10-24