[英]How to update and delete array of elements from child component and pass that to parent component in ReactJs
編輯:我創建了一個代碼框。 鏈接在這里:
https://codesandbox.io/s/musing-rgb-ikq33?from-embed
我有一個場景,我需要從子組件更新父組件中的數組。
例如,我正在從表單添加數組內容,所以如果我在子組件中有 7 個項目(我從子組件添加並從表單將它們一一傳遞給父組件)。
如何在不改變原始數組的情況下編輯/更新單個數組行?
添加工作正常,我需要編輯單個項目並在父組件中更新它(包含來自子組件的所有數組元素),但似乎沒有突變就無法完成。
父組件:
handlePlansClick = (planData) => {
this.setState(state => ({
lead_plans: [...state.lead_plans, planData]
}));
}
Parent組件中的子組件聲明:
<LeadPlans handlePlansClick={this.handlePlansClick} existing_lead_plans={this.state.lead_plans}
must_contain_lead_plan={this.state.must_contain_lead_plan} lead_id={lead_id} updateMode={updateMode}/>
為了從子表單添加到父表單,我正在使用:
this.props.handlePlansClick({
id: Date.now(),
year: year,
probability: probability,
plan2: plan2,
plan3: plan3,
fee: fee,
addcosts: addcosts
}
);
對於更新:
const {lead_id, lead_plans, year, probability, plan2, plan3, fee} = this.state;
const new_lead = {
id: lead_id,
year,
probability,
plan2,
plan3,
fee,
};
const updated_lead_plans = lead_plans.map((lead) => lead.id === lead_id ? new_lead : lead);
this.setState({
lead_plans: updated_lead_plans,
year: '',
probability: '',
plan2: '',
plan3: '',
fee: '',
addcosts: '',
newFieldsEditMode: false,
LeadPlanSaveUpdateDialogOpen: false
});
現在,它按預期工作,但問題是它沒有更新我需要更新數組項的父數組。 它僅更新我不想更新的子組件中的所有內容。
下面的代碼需要修復,因為我想刪除現有項目並再次更新父數組中包含所有元素數組的更新項目:
const updated_lead_plans = lead_plans.map((lead) => lead.id === lead_id ? new_lead : lead);
this.setState({
lead_plans: updated_lead_plans,
year: '',
probability: '',
plan2: '',
plan3: '',
fee: '',
addcosts: '',
newFieldsEditMode: false,
LeadPlanSaveUpdateDialogOpen: false
});
同樣,對於刪除我正在使用:
this.setState(prevState => ({lead_plans: prevState.lead_plans.filter(lead_offer_rec => lead_offer_rec !== lead_plan_row)}));
但它只在子組件中工作,因為我想刪除項目並使用刪除的項目更新我的父數組。
如何從子級獲取編輯/更新/刪除並將更新后的數組再次傳遞給父級?
在 React 中,數據流應始終從父組件流向子組件,反之亦然。您可以使用像Redux
這樣的“全局 State 管理工具”將數據從一個組件傳遞到任何其他組件並更新根state object。 此外Redux
在實現時有很多樣板,所以如果應用程序很簡單,您可以使用MobX
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.