How I Should Use Shouldcomponentupdate Here To Update Parent State In React.js?
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:
create a new method in
FilterBar, name it whatewer you want and pass it as a prop toCategoriescomponent. This method will accept just one argument - array of categories. This method will updateFilterBarstate.categories.in
Categoriescomponent, removestate.selectedandsaveSelectedmethod. In places where you are usingsaveSelectedreplace it with prop (function/method) passed fromFilterBar.
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:
- add
visible: trueto theFilterBarstate - add
onResetmethod to the same component:
onReset = () => {
this.setState(
state => ({ visible: false }),
() => {
this.setState({ visible: true });
}
);
};
- update reset button:
onClick={this.onReset} - 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?"