Reactjs - 排序状态对象的数组 [英] Reactjs - Sorting an array of objects in state

查看:1488
本文介绍了Reactjs - 排序状态对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚是怎么回事,我的阵营组件状态时拖拽正拖放界面重新排序菜单项。在我的code我有被传递的对象与项目从父组件的状态数组中的菜单组件是完全拖动排序。

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.

在处理拖N - 下降排序,我做我所有的数组操作别处,然后覆盖状态阵列的setState()或不变更新,以便菜单将重新呈现。问题是,当我尝试这样做,名单上被渲染重新排序()返回其原始状态(或有时是随机排序)。我不知道是怎么回事,可能是东西,我做错了,但在同一时间,我已经竭尽所能。因此它看起来有点像与之反应,我不是追赶。

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} />
}

更新
它看起来像这不是一个问题作出反应,这是与拖n的问题滴,我用图书馆。我最近有一个不同的库集成,所有靠不住的状态更新就走开了。

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.

推荐答案

这可能与要求您在阵列循环的项目提供唯一ID,然后用<$ C $嵌入作出反应的虚拟DOM和解算法做C>键= {item.id} 。下面是更多的细节讨论:

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

这篇关于Reactjs - 排序状态对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆