0
votes

I'm trying to create a hierarchical menu selection component with 3 levels.

The structure is like this:

CategoryLv0
-->CategoryLv1
---->CategoryLv2

After clicking on a CategoryLv0 node and the initial render of the CategoryLv1 nodes finishes everything is fine. The issue I'm having is when I then click on a CategoryLv1 node it should send an updated prop from the parent component down the component chain to trigger componentWillReceiveProps at the CategoryLv1 level. This would setState and render the CategoryLv2 branch from that node. However the componentWillReceiveProps hook for CategoryLv1 is never called for some reason. The first level (CategoryLv0) works as expected and receives updated props allowing me to setState in it's componentWillReceiveProps to trigger a rerender. It seems like the subsequent levels should work as lv0 works but that's not the case.

I've included an expo snack so you can see it in action.

EDIT The snack has been updated to remove redundant state in the child components, componentWillReceiveProps and ADD extraData={this.props} to the flatLists Expo Snack of ComponentSelectionComponent

<div data-snack-id="SkcBrXsMG" data-snack-platform="android" data-snack-preview="true" data-snack-theme="dark" style="overflow:hidden;background:#212733;border:1px solid rgba(0,0,0,.16);border-radius:4px;height:505px;width:100%"></div>
<script async src="https://snack.expo.io/embed.js"></script>
1
Looking at the code, I feel like it may be easier to trace/understand if you simplify things. First off, you appear to be copying over props to state in all of your category classes. Why not just access the props directly? Putting the value in state is unnecessary. Also, once you remove the redundant state issue, you can make all of your category* into pure components. Then you check the master state is update properly. Also, look into FlatList's extraData prop. - Travis White
Hey thanks for the help! Yea i actually wasn't doing all the setState in the category classes before, and it was the same issue. Also the category classes are already PureComponents. But yes I have removed the redundant setState's and updated the Snack. According to the console.log at the parent component render, i can see the states are being set correctly, its just not getting propagated correctly. Please have a look! I'll read into extra data right now. - rt_
extraData was the thing! Thanks a bunch. in CategoryLv0 i just needed to set extraData={this.props} in the FlatList I will update the snack again so people can see - rt_

1 Answers

1
votes

Travis pointed me in the right direction. The answer is that I needed to use the extraData prop in the child component's FlatList. Without it, it didn't know to rerender.

So since I am passing a master state of the menu as a prop to the child component, I set extraData={this.props} to access the state. And it works!