React CSSTransitionGroup deleted item shifted to end

依然范特西╮ 提交于 2019-12-11 12:32:05

问题


I'm using the CSSTransitionGroup addon to animate the addition and removal of items to an array. When adding, the animation performs as expected, but on remove the removed item is shifted to the end before the animation begins. I'm fairly new to React, butI assume there is something going on under the hood with how React reconciles array changes?

http://jsfiddle.net/alalonde/0kztn19d


回答1:


Your remove statement goes wrong because of react's key specifics. See explanation here of dynamic components (which is what you have), and how to use them with 'key`.

To repair, change your return statement inside the mapping of children to:

return <Item key={item} item={item}/>;

And create a new (pure) component called <Item>:

var Item = React.createClass({
  render: function() {
    return <div>{this.props.item}</div>;
  }
});

I tried this in your fiddle and it works. Hopefully this link will give you the updated fiddle.

BTW: In line with fiddle, my changes are quick and dirty solution: react expects keys to be unique AND related to the content of the item in the list. My example does meet the second requirement (Please do NOT use the mapping index as the key), but it fails on the first: if you add, then delete, then add, the example code would produce a next item with the same number (not unique), so it fails.



来源:https://stackoverflow.com/questions/35979761/react-csstransitiongroup-deleted-item-shifted-to-end

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