【问题标题】:How to push new object in an array?如何在数组中推送新对象?
【发布时间】:2018-10-28 23:15:05
【问题描述】:

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

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

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

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

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

【讨论】:

  • 谢谢,我没有意识到@@
猜你喜欢
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
  • 2020-02-03
相关资源
最近更新 更多