Skip to content

Commit

Permalink
feat: form 添加 getInitialValues 方法 (#45)
Browse files Browse the repository at this point in the history
* feat: form 添加 getInitialValues 方法

* docs: doc

* feat: form 添加 getInitialValues 方法
  • Loading branch information
crazyair authored Aug 26, 2020
1 parent a045db0 commit c1a17ed
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 6 deletions.
1 change: 1 addition & 0 deletions docs/apis/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ nav:
| params | 当前表单状态(需用到 `submit` 类型) | <a href="/apis/hooks#paramsobjtype">ParamsObjType</a> | - |
| submitComponentProps |`submit` 类型参数结合使用(用户无需传) | <a href="/types/submit#api">YFormSubmitComponentProps</a> | - |
| minBtnLoadingTime | 按钮最低 loading 时间 | number | 500 |
| getInitialValues | 获取表单默认值 | - | - |

## YForm.Items

Expand Down
25 changes: 25 additions & 0 deletions docs/examples/demo/demo5.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* title: getInitialValues 使用
* desc: 快捷方式用来获取表单初始化数据
*/
import React from 'react';
import { YForm } from 'yforms';

export default () => {
const onFinish = (values: any) => {
console.log('Success:', values);
};

return (
<YForm
onFinish={onFinish}
getInitialValues={async () => Promise.resolve({ name: '张飞', money: '99' })}
>
{[
{ type: 'input', label: '姓名', name: 'name' },
{ type: 'money', label: '金额', name: 'money' },
{ type: 'submit' },
]}
</YForm>
);
};
4 changes: 4 additions & 0 deletions docs/examples/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ nav:

<code src="./demo/demo2.tsx" />

## getInitialValues

<code src="./demo/demo5.tsx" />

## jsx 写法

<code src="./demo/demo4.tsx" />
1 change: 1 addition & 0 deletions packages/yforms/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"numbro": "^2.3.1",
"nzh": "^1.0.4",
"immutable": "^4.0.0-rc.12",
"ahooks": "^2.5.0",
"warning": "^4.0.3"
},
"license": "MIT"
Expand Down
29 changes: 23 additions & 6 deletions packages/yforms/src/YForm/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { merge, concat, mapKeys, omit, find, get, set, forEach } from 'lodash';
import classNames from 'classnames';
import { FormProps, FormInstance } from 'antd/lib/form';
import warning from 'warning';
import { usePersistFn } from 'ahooks';

import baseItemsType, { YFormItemsType, modifyType } from './ItemsType';
import Items, { FormatFieldsValue, YFormItemProps } from './Items';
Expand Down Expand Up @@ -84,6 +85,7 @@ export interface YFormProps<T = any> extends Omit<FormProps, 'form'>, YFormConfi
oldValues?: T;
offset?: YFormItemProps['offset'];
minBtnLoadingTime?: number;
getInitialValues?: (p?: any) => Promise<Object> | Object;
}

export function useFormatFieldsValue() {
Expand Down Expand Up @@ -137,8 +139,10 @@ const InternalForm = React.memo<YFormProps>((thisProps) => {
submit,
initialValues,
minBtnLoadingTime = 500,
getInitialValues,
...rest
} = _props;

const [form] = useForm(propsForm);
const formatRef = useRef([]);
const { resetFields, getFieldsValue } = form;
Expand All @@ -165,6 +169,20 @@ const InternalForm = React.memo<YFormProps>((thisProps) => {
[submit],
);

const [_getInitialValues, setGetInitialValues] = useState({});
const [getLoading, setGetLoading] = useState(true);
const immutableGetDetail = usePersistFn((...p) => getInitialValues && getInitialValues(...p));

// 传了 getInitialValues 则使用该数据,没传则使用 initialValues、loading
const _initialValues = getInitialValues ? _getInitialValues : initialValues;
const _loading = getInitialValues ? getLoading : loading;
useEffect(() => {
(async () => {
setGetInitialValues(await immutableGetDetail());
setGetLoading(false);
})();
}, [immutableGetDetail]);

useEffect(() => {
return () => {
clearTimeout(timeOut.current);
Expand Down Expand Up @@ -246,13 +264,13 @@ const InternalForm = React.memo<YFormProps>((thisProps) => {

// deFormatFieldsValue 第一次为空需要下面 set(deFormatValues, name, value) 设置值
// 当执行 resetFields 后,就需要 deFormatFieldsValue 的格式化。
const deFormatValues = submitFormatValues(initialValues, deFormatFieldsValue);
const deFormatValues = submitFormatValues(_initialValues, deFormatFieldsValue);

const handleDeFormatFieldsValue = useCallback(
(data: FormatFieldsValue) => {
const { name, format } = data;
const parentValue = getParentNameData(initialValues, name);
const value = format(get(initialValues, name), parentValue, initialValues);
const parentValue = getParentNameData(_initialValues, name);
const value = format(get(_initialValues, name), parentValue, _initialValues);
if (!find(formatRef.current, { name })) {
// 如果上一级是 undefined,则不处理该字段。(List add 会生成空对象)
if (parentValue !== undefined) {
Expand All @@ -264,9 +282,8 @@ const InternalForm = React.memo<YFormProps>((thisProps) => {
}
}
},
[initialValues, form, deFormatValues, onDeFormatFieldsValue],
[_initialValues, form, deFormatValues, onDeFormatFieldsValue],
);

const providerProps = mergeWithDom(
{
form,
Expand All @@ -292,7 +309,7 @@ const InternalForm = React.memo<YFormProps>((thisProps) => {
if ('isShow' in _props && !_props.isShow) {
return null;
}
if (loading) {
if (_loading) {
return (
<div className="form-spin">
<Spin />
Expand Down
18 changes: 18 additions & 0 deletions packages/yforms/src/YForm/__test__/YFormItems.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -430,4 +430,22 @@ describe('YFormItems', () => {
);
expect(wrapper).toMatchSnapshot();
});
test('getInitialValues', async () => {
const init = { name: '张飞', money: '99' };
const onFinish = (value) => {
expect(value).toEqual(init);
};
const wrapper = await mount(
<YForm onFinish={onFinish} getInitialValues={async () => Promise.resolve(init)}>
{[
{ type: 'input', label: '姓名', name: 'name' },
{ type: 'money', label: '金额', name: 'money' },
{ type: 'submit' },
]}
</YForm>,
);
await delay(0);
wrapper.update();
await wrapper.find('.ant-btn').at(0).simulate('submit');
});
});

0 comments on commit c1a17ed

Please sign in to comment.