【发布时间】:2019-09-20 07:39:20
【问题描述】:
向数组中插入新值有效,但我希望在渲染中更新表格
this.state = {
materials: [
{
material: {id: 1, label: 'm1'},
quantity: 2,
unitPrice: 12,
total: 0
},
{
material: {id: 2, label: 'm2'},
quantity: 4,
unitPrice: 15,
total: 1
}
]
}
handleOnClick(e){
this.state.materials.push(this.state.selectedMaterialUnitID, this.state.quantity, this.state.unitPrice, this.state.total);
console.log(this.state.materials); // this worked fine
}
<tbody>
{materials.map((obj) => {return(
<tr>
<td >{obj.material.label}</td>
<td>{obj.quantity}</td>
<td>{obj.unitPrice}</td>
<td>{obj.total}</td>
</tr>
)})}
</tbody>
<Button varient={"light"} onClick={this.handleOnClick}>Add row</Button>
预期结果是表更新并插入新行时
【问题讨论】:
-
你需要使用
this.setState() -
在此处查看文档:reactjs.org/docs/…
-
永远不要直接改变 this.state,因为之后调用 setState() 可能会替换你所做的改变。