如何在数组中推送新对象?

时间:2018-05-18 13:36:55

标签: javascript reactjs

如何在数组中推送新对象?每当我在反应中运行此代码时,它一直在替换数组中的第一个对象。

   radioButtonVal = (e) => {
    this.radioid = e.target.name;
    this.radiovalue = e.target.value;
    this.radioButtonValTitles = [];
    this.radioButtonValFind = this.radioButtonValTitles.find(x => x.id === this.radioid);
    if(this.radioButtonValFind){
        this.radioButtonValFind.id = this.radioid;
        this.radioButtonValFind.value = this.radiovalue;
    } else {
        this.radioButtonValTitles.push({id: this.radioid, value: this.radiovalue})
    }
}

输出是({object,object})只是替换当前值

预期输出为({object,object},{object,object} ...)

1 个答案:

答案 0 :(得分:0)

问题是每次调用函数时都指定一个空数组

 radioButtonVal = (e) => {
    this.radioid = e.target.name;
    this.radiovalue = e.target.value;
    this.radioButtonValTitles = []; //right here you initiate an empty array
    this.radioButtonValFind = this.radioButtonValTitles.find(x => x.id === this.radioid);
    if(this.radioButtonValFind){
        this.radioButtonValFind.id = this.radioid;
        this.radioButtonValFind.value = this.radiovalue;
    } else {
        this.radioButtonValTitles.push({id: this.radioid, value: this.radiovalue})
    }
}

你应该做的是将radioButtonValTitles保持在你的状态,稍后再引用它们,如下所示:

constructor(props) {
    super(props);

    this.state = {
        radioButtonValTitles: [],
    };  
}

然后像这样修改你的函数:

 radioButtonVal = (e) => {
    const { radioButtonValTitles } = this.state;

    this.radioid = e.target.name;
    this.radiovalue = e.target.value;
    this.radioButtonValFind = radioButtonValTitles.find(x => x.id === this.radioid);
    if(this.radioButtonValFind){
        this.radioButtonValFind.id = this.radioid;
        this.radioButtonValFind.value = this.radiovalue;
    } else {
        this.setState({
            radioButtonValTitles: radioButtonValTitles.push({id: this.radioid, value: this.radiovalue})
        )}
    }
}