我是React的新手,正在从事有关创建收据并向收据添加成分的初学者项目。现在,我在添加新配料来更新收据时遇到问题。在控制台屏幕上成功记录了带有新添加的成分的收据对象,但无法呈现它。
虚拟数据如下:
const data = {
receipts:[
{
id: 1,
title: "Demo Title",
body: "You have to add some ingredients",
ingredients: [
{
id: 1,
title: "Salt"
},
{
id: 2,
title: 'Sugar',
},
],
},
]
}
这是状态:
state = {
receipts: data.receipts,
}
我正在使用handleUpdateForm()更新收据
handleUpdateForm =(attr)=>{
this.updateReceipt(attr);
}
updateReceipt =(attr)=>{
this.setState({
receipts: this.state.receipts.map(r=>{
return Object.assign({},r,{
title: attr.title,
body: attr.body,
ingredients: attr.ingredients,
})
})
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
在handleAddIngredient()内部,我正在通过添加新成分来更新收据。 我尝试使用concat()方法没有成功,在这里我使用了传播运算符,再次发生了同样的事情
handleAddIngredient =(ingTitle, receiptId)=>{
const ingred = this.addIngredient(ingTitle)
const receipts = this.state.receipts.map(receipt=>{
if(receipt.id === receiptId){
return Object.assign({},receipt,{
ingredients: [...receipt.ingredients,ingred]
})
}else{
return receipt
}
})
this.setState({receipts})
}
addIngredient = (ingTitle)=>{
return {
id: this.generateId(),
title: ingTitle,
}
}
generateId = ()=>{
return '_' + Math.random().toString(36).substr(2, 9);
}
render(){
return(
<div>
<Header />
<ReceiptList
receipts={this.state.receipts}
onFormUpdate={this.handleUpdateForm}
onDeleteReceipt={this.handleDeleteReceipt}
onAddIngredient={this.handleAddIngredient}
/>
<ToggleReceipt
onFormSubmit={this.handleSubmitForm}
onAddIngredient={this.handleAddIngredient}
/>
</div>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
答案 0 :(得分:0)
this.setState({ receipts: [ ...this.state.receipts, newReceipt ]})
答案 1 :(得分:0)