简体   繁体   English

React:从多个子组件更新父组件中的 state

[英]React: Updating state in parent component from multiple child components

Am new to react and i encountered a problem while trying this out.我是新来的反应,我在尝试这个时遇到了问题。 I have a 2d array in the parent state which i mapped into several child's components.我在父 state 中有一个二维数组,我将其映射到几个子组件中。 I have a check box in the parent component which when clicked should get the values in the all the child's components and update the 2d array.我在父组件中有一个复选框,单击该复选框时应该获取所有子组件中的值并更新二维数组。 I created a function to do this in the parent component and send as prop to all the child's components but the change is not reflected in the 2d array present in the parent component.我创建了一个 function 来在父组件中执行此操作,并将其作为 prop 发送给所有子组件,但更改未反映在父组件中的二维数组中。 Only the first element in the array is updated.仅更新数组中的第一个元素。 Help me out please.请帮帮我。 The function passed to the child component is传递给子组件的 function 是

    updateStudentScores = (
    index,
    test1,
    test2,
    exams,
    totals,
    grades,
    remks,
    SChek,
    bgrnd
  ) => {
    const elementsIndex = this.state.students.findIndex(
      (element) => element.RealIndex == index
    );

    let newArray = [...this.state.tempStudents];
    newArray[elementsIndex] = {
      ...newArray[elementsIndex],
      Cas1: test1,
      Cas2: test2,
      Exam: exams,
      Total: totals,
      Grade: grades,
      Remark: remks,
      stillChecked: SChek,
      background: bgrnd,
    };
    this.setState({ tempStudents: newArray });
  };

tempStudents is the 2d array in the parent component state. Thanks for your response tempStudents是父组件state中的二维数组。感谢您的回复

The reason it only updates the first element is because when the first child component updates the 2D array it updates the parents state -> which sends it as an updated prop to all children -> causing them all to re-render and lose any inputted data.它只更新第一个元素的原因是因为当第一个子组件更新 2D 数组时它会更新父组件 state -> 将其作为更新的道具发送给所有子组件 -> 导致它们全部重新渲染并丢失任何输入的数据.

You haven't posted any code... but the best way to do this is to have a handler called every time a child changes anything in the 2D array.您还没有发布任何代码……但最好的方法是在每次孩子更改二维数组中的任何内容时调用一个处理程序。 (this is ideal) (这是理想的)

To get your intended functionality you will need the checkbox to change a state that is passed as a prop to all the child components (causing them to re-render) and when that happens you can use a hook or a lifecycle method like "componentDidMount()" to call the handler of the parent with all the values needed to update the array.为了获得预期的功能,您将需要更改 state 的复选框,该复选框作为道具传递给所有子组件(导致它们重新渲染),当发生这种情况时,您可以使用钩子或生命周期方法,如“componentDidMount( )" 以使用更新数组所需的所有值调用父级的处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM