2

I am using Antd Tree to render the tree view of the data, at the beginning the data of the tree is a flat array of objects with each object having a key parentId indicating the parent of that node.

I am then using a function to convert this flat array into hierarchical structure to pass it to the Tree component of the antd library

Please refer this Codesandbox link to see the project code
the flat array is in the data.json file in the src folder

I have done this because pasting the entire code of the project would look clumsy. There is a textbox to enter the new nodes name after selecting an existing node in the tree as the parent of the new node, there are no errors and in the render method in the console the updated state is also getting logged correctly but the tree is not getting rendered reflecting the updated data, I am using shouldComponentUpdate method thinking it would update the DOM if anyone could resolve the problem then it will be a great help
THANK YOU

HubballiHuli
  • 777
  • 7
  • 18

1 Answers1

3

The thing is in the handleAddNode function you update the flatTree from the component's state, but based on the code below:

<Tree
  treeData={this.state.hirarchicalTree}
  onSelect={this.handleOnSelect}
/>

, the treeData prop is given from hirarchicalTree.

The flatTree is up to date, but the hirarchicalTree no, so you need to update it from the flat tree.

The shouldComponentUpdate function doesn't help you, so you can remove it.

You have two options to update the **hirarchicalTree:

  1. Using a setState callback function
  2. Adding componentDidUpdate, and do an update if flatTree is different than before

Basically update the hirarchicalTree from the flatTree in the way you first set it in componentDidMount

After this you'll have another problem at this block:

[...flat].forEach(function(item) {
  all[item.id] = item;
});

As item is an Object, when you assign it, all[item.id] will point to the same reference as item from the flat variable.

So when you'll add children, they will be added also on the items from the flatTree, rendering duplicates in the page. You can see this answer.

You can fix it by doing this:

[...flat].forEach(function(item) {
  all[item.id] = { ...item };
});

This will make a shallow copy, but as we don't have nested fields in item, it's fine.

Working codesandbox here

Andrei
  • 191
  • 5