reactjs React Js,向数组添加新对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48921992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:26:58  来源:igfitidea点击:

React Js, adding new object to an array

reactjsreact-nativereact-routerreact-redux

提问by mohan

I have a text field and a radio button.

我有一个文本字段和一个单选按钮。

I am making an object of these two values and putting inside an array, so that i can store this in Mongo DB.

我正在制作这两个值的对象并将其放入一个数组中,以便我可以将其存储在 Mongo DB 中。

I am constructing an array of objects and trying to iterate for showing the details in a table.

我正在构建一个对象数组并尝试迭代以在表中显示详细信息。

Not able to displaying the details.

无法显示详细信息。

Help needed for this.

为此需要帮助。

 export class AddColumns extends React.Component{

  constructor(props) {
      super(props);
        this.state={
            newItemInput: '',
            selectedValue: '',
            buyItems :[],
            object : {}
        }
      }

  handleChange=(event)=> {
    this.setState({
      ...this.state,
      selectedValue: event.target.value
    });
  };

  change (event){
    this.setState({
      [event.target.name]:event.target.value
    });
  };

addItem(e){
    e.preventDefault();

    const newItemInput = this.state.newItemInput;
    const newRadioValue = this.state.selectedValue;
    const obj = {'item':newItemInput, 'columnType':newRadioValue};
    this.state.buyItems.push(obj);
    console.log(this.state.buyItems);       
  }

  render(){
    const {buyItems,message} = this.state;
    return (
      <div className="container">
          <form className="form-inline" onSubmit={(e) => {this.addItem(e)}}>
            <div className="form-group">
              <label className="sr-only" htmlFor="newItemInput">Add New Item</label>
              <input type ="text" ref ={input => this.newColumn = input} name="newItemInput" placeholder="Modules" value = {this.state.newItemInput} className="form-control" 
                      id="newItemInput" onChange={event => this.change(event)}/>
            </div>

            <div className="k-form-field">
              <input type="radio" name="radio" value="radio1" className="k-radio" onChange={this.handleChange}/>
              <label className="k-radio-label">RadioButton 1</label>

              <input type="radio" name="radio" value="radio2" className="k-radio" onChange={this.handleChange}/>
              <label className="k-radio-label">RadioButton 2</label>

            <div className="form-group">
              <button type="submit" className="btn btn-primary">Add</button><p>{this.state.messgae}</p>
            </div>
          </form>
        <div className="content">
          <div>
                  {
                    buyItems.map((rowdata,i) => { 
                        <div>
                          {rowdata.item}
                        </div>
                    })
                  }
            </div>      
        </div>
      </div>
      );
  }
}

回答by Gorka Hernandez

For the view to update, you must call setState, and not just push an item to the array, you can easily do it using the spread syntax:

要更新视图,您必须调用setState,而不仅仅是将项目推送到数组,您可以使用扩展语法轻松完成:

addItem(e){
    e.preventDefault();
    const newItemInput = this.state.newItemInput;
    const newRadioValue = this.state.selectedValue;
    const obj = {'item':newItemInput, 'columnType':newRadioValue};
    this.setState({
        buyItems: [...this.state.buyItems, obj]
    });
    console.log(this.state.buyItems);       
}

An alternative would be create a copy of the old array, push the new item and proceed to set the state:

另一种方法是创建旧数组的副本,推送新项目并继续设置状态:

addItem(e){
    e.preventDefault();
    const newItemInput = this.state.newItemInput;
    const newRadioValue = this.state.selectedValue;
    const obj = {'item':newItemInput, 'columnType':newRadioValue};
    const newArray = this.state.buyItems.slice(); // Create a copy
    newArray.push(obj); // Push the object
    this.setState({ buyItems: newArray });
    console.log(this.state.buyItems);       
}