React CSSTransitionGroup deleted item shifted to e

2019-08-01 08:59发布

问题:

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.