Skip to content Skip to sidebar Skip to footer

How I Should Use Shouldcomponentupdate Here To Update Parent State In React.js?

I am new in React.js, and I have an issue with parent component state updating. I attached whole code so that don't miss something that can be important. I need my 'Reset' button t

Solution 1:

So, you have categories in FilterBar and Category components state - which are not in sync. Since FilterBar also recieves categories as a prop - that indicates that you don't have a single source of truth for categories. There are at least three places where you are keeping categories in different components states. That is very bad thing and leads to bugs and hard to maintain state. Solution is having categories state in just one place and than passing it down to components which need them (together with methods for updating categories).

Anyway, if reseting only dropdown categories is what you want this is what you can do:

  1. create a new method in FilterBar, name it whatewer you want and pass it as a prop to Categories component. This method will accept just one argument - array of categories. This method will update FilterBar state.categories.

  2. in Categories component, remove state.selected and saveSelected method. In places where you are using saveSelected replace it with prop (function/method) passed from FilterBar.

update

This question actually has nothing to do with component lifecycles or updating parent state.

Here is a thing: you can't control the state you don't own (which is the case with 3rd party components). Some lib authors provide methods for setting initial state or reset, but that is not the case with component library you are using.

In your case, best you can do is to unmount dropdowns ad then mounts them again. It's something like refreshing just the part of the page.

Do this:

  1. add visible: true to the FilterBar state
  2. add onReset method to the same component:
onReset = () => {
    this.setState(
      state => ({ visible: false }),
      () => {
        this.setState({ visible: true });
      }
    );
  };
  1. update reset button: onClick={this.onReset}
  2. conditionally render ButtonToolbar:
returnthis.state.visible ? <ButtonToolbar /> : null// have shortened code just for demonstration purpose

Post a Comment for "How I Should Use Shouldcomponentupdate Here To Update Parent State In React.js?"