Reactjs - Sorting an array of objects in state

丶灬走出姿态 提交于 2019-12-24 13:22:15

问题


I am trying to figure out what is going on with my React component state when re-ordering menu items in a drag-n-drop interface. In my code I have a menu component that is completely drag sortable that gets passed an object with an array of items from the parent components' state.

When handling the drag-n-drop sorting, I do all my array manipulation elsewhere and then overwrite the array in state with setState() or with immutable update so the menu will re-render. The problem is, when I try to do this, the list gets re-ordered on render() back to it's original state (or sometimes a random ordering). I'm not sure what is going on, it may be something that I'm doing wrong, but at the same time I've tried everything. So it's looking like something with React that I'm not catching.

index.js

var _ = require('lodash');
var Update = require('react-addons-update');

//.....more dnd logic.....//

var myArray = _.cloneDeep($this.state.appMenuData.children);

//get dragged element index
var draggedElemIndex = $this._getNodeIdIndex(el);
var draggedElemObj = myArray[draggedElemIndex];

//element was dragged to the bottom of the list
if(sibling == null){
  var newPos = myArray[myArray.length-1].position;

  myArray[draggedElemIndex].position = newPos;
  myArray[draggedElemIndex].changed = true;

  for(var i = draggedElemIndex+1; i <= myArray.length-1; i++){
    myArray[i].position-=1;
  }

  myArray.sort(function(a, b){
    return a.position-b.position;
  });

  var newData = Update($this.state, {
    appMenuData: {children: {$set: myArray}},
  });

 $this.setState(newData); 
}

//.....more dnd logic.....//

render(){
  <Menu data={this.state.appMenuData} />
}

UPDATE It looks like this was not a problem with react, it was a problem with the drag n drop library that I was using. I have recently integrated with a different library and all the wonky state updating went away.


回答1:


This might have to do with React's Virtual DOM reconciliation algorithm that requires you to provide unique IDs for the items in array loops and then embed it with key={item.id}. Here is a discussion with more details:

http://survivejs.com/webpack_react/implementing_notes/#comment-2438453906



来源:https://stackoverflow.com/questions/34010410/reactjs-sorting-an-array-of-objects-in-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!