我有一个文本字段和一个单选按钮。
我正在制作这两个值的对象并放入一个数组,以便我可以将它存储在Mongo DB中。
我正在构建一个对象数组,并尝试迭代以显示表格中的细节。
无法显示详细信息。
需要帮助。
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>
);
}
}
答案 0 :(得分:5)
要更新视图,您必须调用 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);
}
另一种方法是创建旧数组的副本,推送新项目并继续设置状态:
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);
}