fix: Space duplicated key warning (#35311)

close #35305
This commit is contained in:
afc163 2022-04-28 22:23:06 +08:00 committed by GitHub
parent 24fa6a1721
commit 3eabcba073
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 1 deletions

View File

@ -172,4 +172,25 @@ describe('Space', () => {
expect(wrapper.render()).toMatchSnapshot();
});
// https://github.com/ant-design/ant-design/issues/35305
it('should not throw duplicated key warning', () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined);
mount(
<Space>
<div key="1" />
<div />
<div key="3" />
<div />
</Space>,
);
// eslint-disable-next-line no-console
expect(console.error).not.toHaveBeenCalledWith(
expect.stringContaining('Encountered two children with the same key'),
expect.anything(),
expect.anything(),
);
// eslint-disable-next-line no-console
console.error.mockRestore();
});
});

View File

@ -89,11 +89,14 @@ const Space: React.FC<SpaceProps> = props => {
}
const keyOfChild = child && child.key;
// Add `-space-item` as suffix in case simple key string trigger duplicated key warning
// https://github.com/ant-design/ant-design/issues/35305
const defaultKey = `${i}-space-item`;
return (
<Item
className={itemClassName}
key={`${itemClassName}-${keyOfChild || i}`}
key={`${itemClassName}-${keyOfChild || defaultKey}`}
direction={direction}
index={i}
marginDirection={marginDirection}