Skip to content

Commit

Permalink
fix(VirtualList): stabilize children keys in virtual list
Browse files Browse the repository at this point in the history
  • Loading branch information
eternalsky committed Sep 20, 2024
1 parent cc20770 commit f3d1d81
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
28 changes: 27 additions & 1 deletion components/virtual-list/__tests__/index-spec.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { type ReactElement } from 'react';
import VirtualList from '../index';
import '../style';

Expand Down Expand Up @@ -191,4 +191,30 @@ describe('VirtualList', () => {
cy.mount(<App />);
cy.get('.test').should('exist');
});
describe('issue', () => {
it('should not change children key, issue #4942', () => {
const handleItemsRender = cy.spy();
cy.mount(
<div
className="scrollBox"
style={{
height: '200px',
width: '200px',
overflow: 'auto',
}}
>
<VirtualList
itemsRenderer={(items, ref) => {
handleItemsRender((items[0] as ReactElement).key);
return <ul ref={ref}>{items}</ul>;
}}
jumpIndex={50}
>
{generateData(100)}
</VirtualList>
</div>
);
cy.wrap(handleItemsRender).should('be.calledWith', '0-test');
});
});
});
9 changes: 7 additions & 2 deletions components/virtual-list/virtual-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import React, {
type LegacyRef,
type CSSProperties,
type ReactInstance,
type ReactElement,
} from 'react';
import cx from 'classnames';
import { polyfill } from 'react-lifecycles-compat';
Expand Down Expand Up @@ -395,10 +396,14 @@ class VirtualList extends Component<VirtualListProps, VirtualListState> {
const { from, size } = this.state;
const items = [];

const childrenArray = Children.toArray(children);
const childrenArray: Array<ReactElement | undefined | null> = [];

Children.forEach(children, (child: ReactElement | undefined | null) => {
childrenArray.push(child);
});

for (let i = 0; i < size!; ++i) {
items.push(childrenArray![from + i]);
items.push(childrenArray[from + i]);
}

return itemsRenderer!(items, c => {
Expand Down

0 comments on commit f3d1d81

Please sign in to comment.