Commit 787ae53a authored by guang.wu's avatar guang.wu

fix: 修改FormList报错问题

parent 56cf5255
...@@ -75,21 +75,21 @@ const transformMealTimePeriod = mealTimePeriod => { ...@@ -75,21 +75,21 @@ const transformMealTimePeriod = mealTimePeriod => {
* 接口来源数据: [{mealPeriodType: '1', limit: [{mealType: '1', limit: 100},{mealType: '2', limit: 200}]}] * 接口来源数据: [{mealPeriodType: '1', limit: [{mealType: '1', limit: 100},{mealType: '2', limit: 200}]}]
* 转换后表单结构:mealLimit: { limit1: {1: 100, 2: 200}, limit2: {1: 100, 2: 200}} * 转换后表单结构:mealLimit: { limit1: {1: 100, 2: 200}, limit2: {1: 100, 2: 200}}
*/ */
const transformMealLimit = mealLimit => { // const transformMealLimit = mealLimit => {
const mealLimitMap = {}; // const mealLimitMap = {};
mealLimit.forEach(item => { // mealLimit.forEach(item => {
const { mealPeriodType, limit } = item; // const { mealPeriodType, limit } = item;
mealLimitMap[`limit${mealPeriodType}`] = limit.reduce( // mealLimitMap[`limit${mealPeriodType}`] = limit.reduce(
(acc, t) => ({ // (acc, t) => ({
...acc, // ...acc,
[t.mealType]: t.limit, // [t.mealType]: t.limit,
}), // }),
{}, // {},
); // );
}); // });
return mealLimitMap; // return mealLimitMap;
}; // };
/** /**
* 3. 数据模型转换-接口获取数据转换为表单数据 * 3. 数据模型转换-接口获取数据转换为表单数据
...@@ -124,10 +124,10 @@ export const transformVOToFormData = data => { ...@@ -124,10 +124,10 @@ export const transformVOToFormData = data => {
} }
const { mealTimePeriodMap, mealTimePeriodArr } = transformMealTimePeriod(mealTimePeriod); const { mealTimePeriodMap, mealTimePeriodArr } = transformMealTimePeriod(mealTimePeriod);
const mealLimitMap = transformMealLimit(mealLimit); // const mealLimitMap = transformMealLimit(mealLimit);
formData.mealTimePeriod = mealTimePeriodArr; formData.mealTimePeriod = mealTimePeriodArr;
formData.mealLimit = mealLimitMap; formData.mealLimit = mealLimit;
formData.mealTimePeriodMap = mealTimePeriodMap; formData.mealTimePeriodMap = mealTimePeriodMap;
return formData; return formData;
}; };
...@@ -143,6 +143,7 @@ export const transformFormDataToDTO = async (res, selectedMealTypes, selectedMea ...@@ -143,6 +143,7 @@ export const transformFormDataToDTO = async (res, selectedMealTypes, selectedMea
}; };
if (params.pickSelfIds) { if (params.pickSelfIds) {
params.pickselfIds = params.pickSelfIds; params.pickselfIds = params.pickSelfIds;
delete params.pickSelfIds;
} }
/** /**
* 处理餐段 mealTimePeriod * 处理餐段 mealTimePeriod
...@@ -178,26 +179,26 @@ export const transformFormDataToDTO = async (res, selectedMealTypes, selectedMea ...@@ -178,26 +179,26 @@ export const transformFormDataToDTO = async (res, selectedMealTypes, selectedMea
* mealPeriodType 餐段类型:(1早餐,2午餐,4晚餐) * mealPeriodType 餐段类型:(1早餐,2午餐,4晚餐)
* mealType 餐品类型:(1外卖 2 自助餐 4到店) * mealType 餐品类型:(1外卖 2 自助餐 4到店)
*/ */
const limits = []; // const limits = [];
res.mealLimit && // res.mealLimit &&
Object.keys(res.mealLimit).forEach(item => { // Object.keys(res.mealLimit).forEach(item => {
const mealPeriodType = item.replace('limit', ''); // const mealPeriodType = item.replace('limit', '');
if (selectedMealSections[mealPeriodType]) { // if (selectedMealSections[mealPeriodType]) {
const json = { // const json = {
mealPeriodType, // mealPeriodType,
limit: [], // limit: [],
}; // };
Object.keys(res.mealLimit[item]).forEach(t => { // Object.keys(res.mealLimit[item]).forEach(t => {
if (selectedMealTypes.includes(t)) { // if (selectedMealTypes.includes(t)) {
json.limit.push({ // json.limit.push({
mealType: t, // mealType: t,
limit: res.mealLimit[item][t], // limit: res.mealLimit[item][t],
}); // });
} // }
}); // });
limits.push(json); // limits.push(json);
} // }
}); // });
params.mealLimit = limits; // params.mealLimit = limits;
return params; return params;
}; };
import React from 'react';
import { Form, Row, Col } from 'antd';
import { mealType, mealSections } from '../staticData';
import MealLimit from './MealLimit';
/**
* 渲染 企业单笔消费限额 二维表单项目
*/
const MealLimitsFormList = (meals, selectedMealTypes) => (
<Form.List name="mealLimit" key="mealLimit">
{mealLimitsFields => (
<>
{Object.keys(meals).map(meal => (
<Form.Item
key={`${mealSections[meal]}`}
label={`${mealSections[meal]}订单`}
required
labelCol={{ span: 4 }}
wrapperCol={{ span: 20 }}
>
<Form.List
name={`limit${meal}`}
key={`${meal}limit`}
required
wrapperCol={{ span: 21 }}
>
{mealLimitsFieldsList => (
<Row key={`row${meal}`}>
{selectedMealTypes.map((t, i) => (
<Col span={7} offset={i ? 1 : 0} key={t}>
<MealLimit value={t} label={mealType[t]} name={`${t}`} />
</Col>
))}
</Row>
)}
</Form.List>
</Form.Item>
))}
</>
)}
</Form.List>
);
export default MealLimitsFormList;
import React from 'react';
import { Form, Row, Col, Input } from 'antd';
import { mealType, mealSections } from '../staticData';
import MealLimit from './MealLimit';
/**
* 渲染 企业单笔消费限额 二维表单项目
*/
const MealLimitsFormList = (meals, selectedMealTypes) => (
<Form.List name="mealLimit" key="mealLimit">
{() => (
<>
{Object.keys(meals).map((meal, i) => (
<Row key={`meal${meal}`}>
<Col span={0}>
<Form.Item
label=""
name={[i, 'mealPeriodType']}
labelCol={{ span: 0 }}
wrapperCol={{ span: 0 }}
>
<Input type="hidden" value={meal} />
</Form.Item>
</Col>
<Col span={24}>
<Form.Item
label={`${mealSections[meal]}订单`}
required
labelCol={{ span: 4 }}
wrapperCol={{ span: 20 }}
>
<Form.List name={[i, 'limit']} required wrapperCol={{ span: 21 }}>
{() => (
<Row key={`row${meal}`}>
{selectedMealTypes.map((t, j) => (
<Col key={`col${t}`} span={7}>
<Row>
<Col span={0}>
<Form.Item
label=""
name={[j, 'mealType']}
labelCol={{ span: 0 }}
wrapperCol={{ span: 0 }}
>
<Input type="hidden" value={t} />
</Form.Item>
</Col>
<Col span={24} offset={j ? 1 : 0}>
<MealLimit label={mealType[t]} name={[j, 'limit']} />
</Col>
</Row>
</Col>
))}
</Row>
)}
</Form.List>
</Form.Item>
</Col>
</Row>
))}
</>
)}
</Form.List>
);
export default MealLimitsFormList;
...@@ -3,10 +3,11 @@ import { Form, InputNumber } from 'antd'; ...@@ -3,10 +3,11 @@ import { Form, InputNumber } from 'antd';
import { validateRequired, isCheckPriceTwoDecimal } from '@/utils/validator'; import { validateRequired, isCheckPriceTwoDecimal } from '@/utils/validator';
const MealLimit = props => ( const MealLimit = props => (
// console.log('props :>> ', props);
<Form.Item <Form.Item
label={`${props.label}限额`} label={`${props.label}限额`}
name={props.name} name={props.name}
value={props.value} initialValue={props.value}
labelCol={{ span: 10 }} labelCol={{ span: 10 }}
wrapperCol={{ span: 14 }} wrapperCol={{ span: 14 }}
rules={[ rules={[
...@@ -17,5 +18,4 @@ const MealLimit = props => ( ...@@ -17,5 +18,4 @@ const MealLimit = props => (
<InputNumber addonAfter="元" max={999.99} /> <InputNumber addonAfter="元" max={999.99} />
</Form.Item> </Form.Item>
); );
export default MealLimit; export default MealLimit;
/* eslint-disable no-unused-expressions */
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { notification } from 'antd'; import { notification } from 'antd';
import { unstable_batchedUpdates } from 'react-dom';
import { BetaSchemaForm } from '@ant-design/pro-components'; import { BetaSchemaForm } from '@ant-design/pro-components';
import { layout, getBaseFormItem } from './staticData'; import { layout, getBaseFormItem } from './staticData';
import { checkConfirm, transformVOToFormData, transformFormDataToDTO } from './bll'; import { checkConfirm, transformVOToFormData, transformFormDataToDTO } from './bll';
...@@ -9,27 +11,14 @@ import { apiEnterpriseInfo, apiNewEnterprise, apiEditEnterprise } from './servic ...@@ -9,27 +11,14 @@ import { apiEnterpriseInfo, apiNewEnterprise, apiEditEnterprise } from './servic
const CustomerInfo = props => { const CustomerInfo = props => {
const [selectedMealSections, setSelectedMealSections] = useState([]); // 选中的餐段 const [selectedMealSections, setSelectedMealSections] = useState([]); // 选中的餐段
const [selectedMealTypes, setSelectedMealTypes] = useState([]); // 选中的餐品类型 const [selectedMealTypes, setSelectedMealTypes] = useState([]); // 选中的餐品类型
const [pageLoading, setPageLoading] = useState(false); // 页面加载状态 const refForm = useRef(null);
const refForm = useRef();
/** /**
* 7. 表单关闭 * 7. 表单关闭
* @param {boolean} isRefresh 是否刷新列表 * @param {boolean} isRefresh 是否刷新列表
*/ */
const closeModal = isRefresh => { const closeModal = isRefresh => {
if (typeof props.onClose === 'function') { if (!isRefresh && typeof props.onClose === 'function') {
props.onClose(!!isRefresh); props.onClose(isRefresh === 0);
}
setSelectedMealTypes([]);
setSelectedMealSections({});
refForm.current.setFieldsValue({
mealLimit: [],
});
};
const onOpenChange = v => {
if (!v) {
closeModal(!1);
} }
}; };
...@@ -50,7 +39,7 @@ const CustomerInfo = props => { ...@@ -50,7 +39,7 @@ const CustomerInfo = props => {
const resp = await api(data); const resp = await api(data);
if (resp && resp.data) { if (resp && resp.data) {
// 保存成功后刷新列表 // 保存成功后刷新列表
closeModal(!0); closeModal(0);
notification.success({ message: '保存成功!' }); notification.success({ message: '保存成功!' });
} }
}; };
...@@ -77,11 +66,11 @@ const CustomerInfo = props => { ...@@ -77,11 +66,11 @@ const CustomerInfo = props => {
// 注意 须先set 再from.setFieldsValue 防止丢失数据 // 注意 须先set 再from.setFieldsValue 防止丢失数据
setSelectedMealTypes(mt); setSelectedMealTypes(mt);
refForm.current.setFieldsValue({ refForm.current?.setFieldsValue?.({
mealType: mt, mealType: mt,
}); });
} catch { } catch {
refForm.current.setFieldsValue({ refForm.current?.setFieldsValue?.({
mealType: selectedMealTypes, mealType: selectedMealTypes,
}); });
} }
...@@ -104,12 +93,12 @@ const CustomerInfo = props => { ...@@ -104,12 +93,12 @@ const CustomerInfo = props => {
setSelectedMealSections(values); setSelectedMealSections(values);
// 餐段都没选 则设置为空数组 // 餐段都没选 则设置为空数组
if (Object.keys(values).length === 0) { if (Object.keys(values).length === 0) {
refForm.current.setFieldsValue({ refForm.current?.setFieldsValue?.({
mealTimePeriod: null, mealTimePeriod: null,
}); });
} }
// 触发验证当前自段 是否显示表单提示 // 触发验证当前自段 是否显示表单提示
refForm.current.validateFields(['mealTimePeriod']); refForm.current?.validateFields?.(['mealTimePeriod']);
}; };
/** /**
...@@ -117,20 +106,33 @@ const CustomerInfo = props => { ...@@ -117,20 +106,33 @@ const CustomerInfo = props => {
* 把接口数据转换成表单需要的数据格式 * 把接口数据转换成表单需要的数据格式
*/ */
const getInfo = async () => { const getInfo = async () => {
if (!props.id) { // if (!props.id) {
return {}; // return {};
} // }
const res = await apiEnterpriseInfo(props.id); const res = await apiEnterpriseInfo(props.id);
if (res && res.data) { if (res && res.data) {
// 转换成表单需要的数据 // 转换成表单需要的数据
const formData = transformVOToFormData(res.data); const formData = transformVOToFormData(res.data);
// 选中的餐品类型
setSelectedMealTypes(formData.mealType); /**
// 选中的餐段 * 使用setTimeout 的原因是防止 setState的时候 refForm丢失引用
setSelectedMealSections(formData.mealTimePeriodMap); * 导致 refForm.current.validateFields 报错
return formData; * 先渲染完表单再setState
* */
// setTimeout(() => {
// // setState 会导致组件重新渲染 为了防止多次渲染 使用 unstable_batchedUpdates 之后
// // React 18 会优化该问题
unstable_batchedUpdates(() => {
// 选中的餐品类型
setSelectedMealTypes(formData.mealType);
// 选中的餐段
setSelectedMealSections(formData.mealTimePeriodMap);
});
// });
// return formData;
refForm.current?.setFieldsValue?.(formData);
} }
return {}; // return {};
}; };
useEffect(() => { useEffect(() => {
...@@ -142,13 +144,13 @@ const CustomerInfo = props => { ...@@ -142,13 +144,13 @@ const CustomerInfo = props => {
} }
}, [props.visible]); }, [props.visible]);
const formItem = getBaseFormItem({ const formColumns = getBaseFormItem({
onChangeMealType, onChangeMealType,
onChangeMealSection, onChangeMealSection,
id: props.id, id: props.id,
selectedMealSections, selectedMealSections,
selectedMealTypes, selectedMealTypes,
form: refForm.current, refForm,
}); });
return ( return (
...@@ -160,15 +162,14 @@ const CustomerInfo = props => { ...@@ -160,15 +162,14 @@ const CustomerInfo = props => {
modalProps={{ modalProps={{
maskClosable: false, maskClosable: false,
destroyOnClose: true, destroyOnClose: true,
confirmLoading: pageLoading,
}} }}
request={getInfo} // request={getInfo}
formRef={refForm} formRef={refForm}
onOpenChange={onOpenChange} onOpenChange={closeModal}
layout="horizontal" layout="horizontal"
{...layout} {...layout}
onFinish={submitForm} onFinish={submitForm}
columns={formItem} columns={formColumns}
/> />
); );
}; };
......
import React from 'react'; import React from 'react';
import moment from 'moment'; import moment from 'moment';
import MealSection from './components/MealSection'; import MealSection from './components/MealSection';
import MealFormListLimit from './components/MealFormListLimit'; import MealFormListLimit from './components/MealFormListLimitForm';
import { getPickSelf } from './bll'; import { getPickSelf } from './bll';
const hideEnums = { hidePrice: '隐藏商品价格', hideImage: '隐藏商品图片' }; const hideEnums = { hidePrice: '隐藏商品价格', hideImage: '隐藏商品图片' };
...@@ -36,8 +36,8 @@ const checkTime = (arr, current) => { ...@@ -36,8 +36,8 @@ const checkTime = (arr, current) => {
return valid; return valid;
}; };
// 验证餐段 // 验证餐段
const validateMeals = (form, selectedMealSections) => { const validateMeals = (refForm, selectedMealSections) => {
const { mealTimePeriod = [] } = form.getFieldValue(); const { mealTimePeriod = [] } = refForm.current?.getFieldValue?.() || {};
const arr = []; const arr = [];
let validTime = false; let validTime = false;
mealTimePeriod.forEach(item => { mealTimePeriod.forEach(item => {
...@@ -68,7 +68,7 @@ export const getBaseFormItem = options => { ...@@ -68,7 +68,7 @@ export const getBaseFormItem = options => {
onChangeMealType, onChangeMealType,
selectedMealSections, selectedMealSections,
onChangeMealSection, onChangeMealSection,
form, refForm,
} = options; } = options;
const baseColumn = [ const baseColumn = [
...@@ -129,7 +129,7 @@ export const getBaseFormItem = options => { ...@@ -129,7 +129,7 @@ export const getBaseFormItem = options => {
renderFormItem: () => ( renderFormItem: () => (
<MealSection <MealSection
meals={selectedMealSections} meals={selectedMealSections}
validateMeals={() => validateMeals(form, selectedMealSections)} validateMeals={() => validateMeals(refForm, selectedMealSections)}
onChangeSection={onChangeMealSection} onChangeSection={onChangeMealSection}
/> />
), ),
......
...@@ -30,7 +30,6 @@ const BusinessCustomer = () => { ...@@ -30,7 +30,6 @@ const BusinessCustomer = () => {
}; };
const onClose = refresh => { const onClose = refresh => {
console.log(3);
setVisible(false); setVisible(false);
refresh && refTable.current.reload(); refresh && refTable.current.reload();
}; };
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment