Skip to content

Commit 6794ec0

Browse files
authored
fix: List should not crash when it's not a array value (#175)
1 parent 438e366 commit 6794ec0

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/List.tsx

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,17 @@ const List: React.FunctionComponent<ListProps> = ({ name, children }) => {
9797
},
9898
};
9999

100+
let listValue = value || [];
101+
if (!Array.isArray(listValue)) {
102+
listValue = [];
103+
104+
if (process.env.NODE_ENV !== 'production') {
105+
warning(false, `Current value of '${prefixName.join(' > ')}' is not an array type.`);
106+
}
107+
}
108+
100109
return children(
101-
(value as StoreValue[]).map(
110+
(listValue as StoreValue[]).map(
102111
(__, index): ListField => {
103112
let key = keyManager.keys[index];
104113
if (key === undefined) {

tests/list.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import React from 'react';
22
import { act } from 'react-dom/test-utils';
33
import { mount } from 'enzyme';
4+
import { resetWarned } from 'rc-util/lib/warning';
45
import Form, { Field, List } from '../src';
56
import { Input } from './common/InfoField';
67
import { changeValue, getField } from './common';
@@ -67,6 +68,26 @@ describe('Form.List', () => {
6768
});
6869
});
6970

71+
it('not crash', () => {
72+
// Empty only
73+
mount(
74+
<Form initialValues={{ list: null }}>
75+
<Form.List name="list">{() => null}</Form.List>
76+
</Form>,
77+
);
78+
79+
// Not a array
80+
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
81+
resetWarned();
82+
mount(
83+
<Form initialValues={{ list: {} }}>
84+
<Form.List name="list">{() => null}</Form.List>
85+
</Form>,
86+
);
87+
expect(errorSpy).toHaveBeenCalledWith("Warning: Current value of 'list' is not an array type.");
88+
errorSpy.mockRestore();
89+
});
90+
7091
it('operation', async () => {
7192
let operation;
7293
const [wrapper, getList] = generateForm((fields, opt) => {

0 commit comments

Comments
 (0)