如何在ReactJs中将更新的数组对象从子组件传递到父组件

我在工作正常的组件中添加,编辑,更新和删除数组元素。

问题是我无法对父组件执行相同的处理,因为我需要将该数组数据传递给父组件。

数组在子组件中有项目(也将该项目发送到父组件数组)

更新(也更新实际一项,但也更新父组件数组中的相似对象)

删除也一样。

在子组件中执行所有这些操作时,我无法更新父阵列。

我想在我的父组件中更新数组。 下面是代码。

子组件:

// child component saving element in an array
    saveLeadPlanDialog = () => {

        const {updateMode, lead_id, year, probability, plan2, plan3, fee, addcosts} = this.state;

        // here i am setting that data in child component
        this.setState(state => ({
            lead_plans: [...state.lead_plans, {
                id: Date.now(),
                year: year,
                probability: probability,
                plan2: plan2,
                plan3: plan3,
                fee: fee,
                addcosts: addcosts
            }]
        }));

        // here i am sending that data to parent component.
        this.props.plansClick({
                id: Date.now(),
                year: year,
                probability: probability,
                plan2: plan2,
                plan3: plan3,
                fee: fee,
                addcosts: addcosts
            }
        );
    }

// here i am doing delete process in child component
handleRemoveFields = () => {
        const {updateMode, lead_plan_row} = this.state;
        this.setState(prevState => ({lead_plans: prevState.lead_plans.filter(lead_offer_rec => lead_offer_rec !== lead_plan_row)}));
    };

// updating in child component
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
            });

父组件:

 // parent component method.
    handlePlansClick = (planData) => {
        // this is parent componet, here i need to do update, delete the array object which got updation and deletion in child component
        // it alwaya adds item right now.
        this.setState(state => ({
            lead_plans: [...state.lead_plans, planData]
        }));
    }

我也需要在父组件中执行所有这些过程。

有没有更好的方法来处理这种情况?

我如何也可以在父组件中获取更新,编辑,删除的项和操作?

因此,子级和父级在数组中都显示相同的数组组件数据。

评论
  • asaepe
    asaepe 回复

    您应该在此处应用单一的真理原则。仅在父级中更新数据(使用传递给子级的回调(如您当前所做的那样)),然后将结果作为道具传递给子级。这样,数据将始终在两个组件中同步。