首页 > 解决方案 > 如何在数组中推送新对象?

问题描述

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

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

标签: javascriptreactjs

解决方案


问题是每次调用函数时都分配一个空数组

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

推荐阅读