简体   繁体   English

React.js-对处于状态的对象数组进行排序

[英]Reactjs - Sorting an array of objects in state

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. 我想弄清楚在拖放界面中对菜单项重新排序时React组件状态是怎么回事。 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. 在处理拖放排序时,我在其他地方进行了所有数组操作,然后使用setState()或不可变更新覆盖处于状态的数组,因此菜单将重新呈现。 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). 问题是,当我尝试执行此操作时,列表在render()上重新排序回到其原始状态(有时是随机排序)。 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. 因此,看起来像React的某些东西我并没有抓住。

index.js 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. 更新看起来这不是react的问题,这是我使用的drag n drop库的问题。 I have recently integrated with a different library and all the wonky state updating went away. 我最近与一个不同的库集成在一起,所有不可靠的状态更新都消失了。

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} . 这可能与React的虚拟DOM协调算法有关,该算法要求您为数组循环中的项目提供唯一的ID,然后将其嵌入key={item.id} Here is a discussion with more details: 这是更详细的讨论:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM