Browse Source

fix: List key (#38431)

* fix: 修复 key

* feat: remove old key

* feat: test

* feat: test

* feat: test
pull/38488/head
叶枫 2 years ago
committed by GitHub
parent
commit
b0598e0d41
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 30
      components/list/__tests__/Item.test.tsx
  2. 17
      components/list/index.tsx

30
components/list/__tests__/Item.test.tsx

@ -1,6 +1,6 @@
import React from 'react';
import React, { useEffect } from 'react';
import List from '..';
import { render } from '../../../tests/utils';
import { pureRender, render } from '../../../tests/utils';
import ConfigProvider from '../../config-provider';
describe('List Item Layout', () => {
@ -204,4 +204,30 @@ describe('List Item Layout', () => {
);
expect(ref.current).toHaveClass('ant-col');
});
it('react key', () => {
const loadId: number[] = [];
const Demo = ({ id }: { id: number }) => {
useEffect(() => {
loadId.push(id);
}, []);
return <div>{id}</div>;
};
const getDom = (id = 1) => (
<List
dataSource={[{ id, title: `ant design` }]}
rowKey={item => item.id}
renderItem={item => (
<List.Item>
<Demo id={item.id} />
</List.Item>
)}
/>
);
const { rerender } = pureRender(getDom(1));
rerender(getDom(3));
rerender(getDom(5));
expect(loadId).toEqual([1, 3, 5]);
});
});

17
components/list/index.tsx

@ -104,8 +104,6 @@ function List<T>({
total: 0,
};
const listItemsKeys: { [index: number]: React.Key } = {};
const triggerPaginationEvent = (eventName: string) => (page: number, pageSize: number) => {
setPaginationCurrent(page);
setPaginationSize(pageSize);
@ -135,9 +133,7 @@ function List<T>({
key = `list-item-${index}`;
}
listItemsKeys[index] = key;
return renderItem(item, index);
return <React.Fragment key={key}>{renderItem(item, index)}</React.Fragment>;
};
const isSomethingAfterLastItem = () => !!(loadMore || pagination || footer);
@ -249,13 +245,14 @@ function List<T>({
let childrenContent = isLoading && <div style={{ minHeight: 53 }} />;
if (splitDataSource.length > 0) {
const items = splitDataSource.map((item: T, index: number) => renderInnerItem(item, index));
const childrenList = React.Children.map(items, (child: React.ReactNode, index: number) => (
<div key={listItemsKeys[index]} style={colStyle}>
childrenContent = grid ? (
<Row gutter={grid.gutter}>
{React.Children.map(items, child => (
<div key={child?.key} style={colStyle}>
{child}
</div>
));
childrenContent = grid ? (
<Row gutter={grid.gutter}>{childrenList}</Row>
))}
</Row>
) : (
<ul className={`${prefixCls}-items`}>{items}</ul>
);

Loading…
Cancel
Save