简体   繁体   English

更新父组件 state 时反应子组件不重新渲染

[英]React child component not rerendering when updating parent component state

I have a parent component where I am updating a nested property on an object in the state of the component.我有一个父组件,我在该组件的 state 中更新 object 上的嵌套属性。 This is the object in the state:这是 state 中的 object:

this.state = {
  classObject: {
    description: {...}, // class description
    mergedClasses: [{
      partialClass: {...}, 
      description: {...}
    }]
  }
}

In the method below I am updating the array mergedClasses inside the classObject object:在下面的方法中,我正在更新classObject object 中的数组mergedClasses

onUpdatingClasses() {
  this.setState(prevState => {
    const classes = prevState.selectedClasses
      .map(selectedClass => {
        const classObject = prevState.class.mergedClasses.find(classObject => selectedClass.id === classObject.id);
        return classObject
          ? {...classObject}
          : {partialClass: selectedClass});

    return {
      classObject: {
        ...prevState.classObject,
        mergedClasses: classes,
      }
    };
  });
}

Then down the component chain, I have a child component that has tabs, and renders one of this classes from the mergedClasses array.然后在组件链中,我有一个具有选项卡的子组件,并从mergedClasses数组呈现这些类之一。 As a default I am setting the first element from the array to render.默认情况下,我将数组中的第一个元素设置为渲染。 I am doing this by setting the value of the tab to the index of the first element from that array like this:我通过将选项卡的值设置为该数组中第一个元素的索引来做到这一点,如下所示:

state = {
  value: this.props.classObject.mergedClasses[0].partialClass.id,
}; 

This works fine as long as I don't update the first element of the array.只要我不更新数组的第一个元素,它就可以正常工作。 Then the component crushes, because the value doesn't get updated with the new first element id.然后组件崩溃,因为该值没有使用新的第一个元素 id 进行更新。 I have tried with checking the props in componentDidUpdate method, but I saw in devtools that it never gets called.我曾尝试检查componentDidUpdate方法中的道具,但我在 devtools 中看到它永远不会被调用。

componentDidUpdate(prevProps) {
  if(prevProps.classObject.mergedClasses[0].partialClass.id !== this.props.classObject.mergedClasses[0].partialClass.id) {
    this.setState({value: 
    this.props.classObject.mergedClasses[0].partialClass.id);
  }
}

What am I doing wrong and how can I make a component to update the state with the new props?我做错了什么,如何制作一个组件来使用新道具更新 state?

You can set the default state in componentDidMount .您可以在componentDidMount中设置默认的 state 。

For example例如

componentDidMount() {
  const {
    classObject: { mergedClasses: [{ partialClass: { id } = {} }] = [{}] } = {},
  } = this.props;
  // now you have no undefined values
  this.setState({ value: id });
}

you could also use defaultValues if you are using classes, as in如果您使用的是类,也可以使用defaultValues ,如

  state: { ... }
...
  defaultValues: { ... // describe default values here if not set }

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

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