场景:封装好的弹框,按钮上加了个loading状态,根据传入的值弹框提交的模块内容不一样。loading更新过后,但是值没有变。
注)写法一loading不更新,写法二loading值更新。
一、写法一
写法一中的 acceptanceReject 函数是一个异步函数,它会在异步操作完成后才会执行 finally 中的代码。这意味着 finally 中的 setLoading(false) 会在 acceptanceReject 函数中所有异步操作完成后才执行,包括 await rejectDataDs.current?.validate()、await getTaskId(instanceId) 和 await postAcceptance(params)。
因此,在写法一中,即使在 acceptanceReject 函数中设置了 setLoading(true),但在 handleSubmit 函数中并没有等待 acceptanceReject 函数中的异步操作完成,所以在 handleSubmit 中立即打印 loading 时,可能仍然是旧值。
/** 提交 */const handleSubmit = () => {switch (type) {case 'one': oneReject();break;case 'two': twoReject();break;case 'three': fourReject();break;default:break;}};const one= async () => {setLoading(true);try {const validate = await rejectDataDs.current?.validate();if (!validate) {return;}console.log('执行了嘛');const { id, instanceId } = formDataDs.current?.toData();const taskIdValue = await getTaskId(instanceId);const params: ItemAcceptance = {...rejectDataDs.current?.toData(),id,instanceId,approveResult: 'N',taskId: taskIdValue?.[0]?.taskId,};debuggerconst res = await postAcceptance(params);handleSuccess(res, 'acceptanceReject');} finally {setLoading(false);}};const two= async () => {const { id, instanceId } = formDataDs.current?.toData();const { approveOpinion } = rejectDataDs.current?.toData();const taskIdValue = await getTaskId(instanceId);const params: DetermineParams = {id,taskId: taskIdValue?.[0]?.taskId,instanceId,approveOpinion,approveResult: 'N',};const res = await postDetermine(params);handleSuccess(res, 'decideReject');};const three= async () => {const {id,pkNo,instanceId,subInstanceId,} = formDataDs.current?.toData();const { approveOpinion } = rejectDataDs.current?.toData();const taskIdValue = await getTaskId(subInstanceId);const params: ApprovalParams = {id,pkNo,taskId: taskIdValue?.[0]?.taskId,instanceId,subInstanceId,approveResult: 'N',approveOpinion,};const res = await postApprove(params);handleSuccess(res, 'approveReject');};
解决方法:因为switch中忘记加异步await了。
二:写法二
写法二中,所有异步操作都在同一个函数中,因此 setLoading(true) 和后续的异步操作是连续执行的,所以可以在后续代码中获取到正确的 loading 值。
const handleSubmit = async () => {setLoading(true);try {const validate = await rejectDataDs.current?.validate();if (!validate) {return;}const { id, instanceId } = formDataDs.current?.toData();const taskIdValue = await getTaskId(instanceId);const params: ItemAcceptance = {...rejectDataDs.current?.toData(),id,instanceId,approveResult: 'N',taskId: taskIdValue?.[0]?.taskId,};console.log('loading', loading);const res = await postAcceptance(params);handleSuccess(res, 'acceptanceReject');} finally {setLoading(false);}};
三、完整代码(问题版本)
封装好的完整代码如下:
import {ApprovalParams,DetermineParams,ItemAcceptance,
} from '@/interface/channelPk/main';
import { languageConfig } from '@/language/language';
import { Button, Form, message, Modal, TextArea } from 'choerodon-ui/pro';
import DataSet from 'choerodon-ui/dataset/data-set/DataSet';
import React, { useEffect, useState } from 'react';
import { LabelLayout } from 'choerodon-ui/pro/lib/form/enum';
import { ButtonColor } from 'choerodon-ui/pro/lib/button/enum';
import {postAcceptance,postApprove,postDetermine,
} from '@/api/channelPk/main';
import {getTaskId,handleCancel,pubPath,
} from '@/pages/channelPk/detail/hook';
import { FieldType } from 'choerodon-ui/dataset/data-set/enum';
import { useHistory } from 'dva';
import { set } from 'choerodon-ui/dataset/object-chain-value';interface HandleRejectProps {visible: boolean;setVisible: (val: boolean) => void;formDataDs: DataSet;type: string;
}let modal: any;
const RejectModel: React.FC<HandleRejectProps> = ({visible,formDataDs,type,setVisible,
}) => {let history = useHistory();const [loading, setLoading] = useState(false);/** ds 驳回 */const rejectDataDs = new DataSet({autoCreate: true,fields: [{name: 'approveOpinion',type: FieldType.string,label: languageConfig('rejectReason', '驳回原因'),placeholder: languageConfig('planceholder.rejectReason','请输入驳回原因',),required: true,},],});useEffect(() => {if (visible) {openModal();}}, [visible]);/** 弹框打开 */const openModal = () => {modal = Modal.open({title: languageConfig('btn.reject', '驳回'),okText: languageConfig('btn.confirm', '确定'),closable: true,children: <Box />,footer: (<div style={{ textAlign: 'right' }}><Buttonloading={loading}color={ButtonColor.primary}onClick={() => handleSubmit()}>{languageConfig('btn.confirm', '确定')}</Button><Buttonloading={loading}onClick={() => {modal.close();setVisible(false);}}>{languageConfig('btn.cancel', '取消')}</Button></div>),});};/** 内容 */const Box = () => {return (<div className="ltc-c7n-style"><div className="customer"><div className="border"></div><FormdataSet={rejectDataDs}labelWidth={80}columns={4}labelLayout={LabelLayout.vertical}className="reject"><TextAreaname="approveOpinion"rows={4}colSpan={4}newLine={true}// maxLength={200}showLengthInfoclearButton/></Form></div></div>);};/** 提交 */const handleSubmit = async () => {const validate = await rejectDataDs.current?.validate();if (!validate) {return;}setLoading(true);switch (type) {case 'acceptance': // 受理驳回await acceptanceReject();break;case 'decide': // 判定驳回await decideReject();break;case 'one': // 战区内未确权-一级审批await oneReject();break;case 'two': // 战区内未确权-二级审批await twoReject();break;case 'four': // 战区内已确权-二级审批await fourReject();break;case 'seven': // 跨战区await sevenReject();break;default:break;}};/** 【受理】驳回 */const acceptanceReject = async () => {const { id, instanceId } = formDataDs.current?.toData();const taskIdValue = await getTaskId(instanceId);const params: ItemAcceptance = {...rejectDataDs.current?.toData(),id,instanceId,approveResult: 'N',taskId: taskIdValue?.[0]?.taskId,};const res = await postAcceptance(params);handleSuccess(res, 'acceptanceReject');};/** 【判定】驳回(跨战区) */const decideReject = async () => {const { id, instanceId } = formDataDs.current?.toData();const { approveOpinion } = rejectDataDs.current?.toData();const taskIdValue = await getTaskId(instanceId);const params: DetermineParams = {id,taskId: taskIdValue?.[0]?.taskId,instanceId,approveOpinion,approveResult: 'N',};const res = await postDetermine(params);handleSuccess(res, 'decideReject');};/** 【战区内未确权-一级审批】驳回 */const oneReject = async () => {const {id,pkNo,instanceId,subInstanceId,} = formDataDs.current?.toData();const { approveOpinion } = rejectDataDs.current?.toData();const taskIdValue = await getTaskId(subInstanceId);const params: ApprovalParams = {id,pkNo,taskId: taskIdValue?.[0]?.taskId,instanceId,subInstanceId,approveResult: 'N',approveOpinion,};const res = await postApprove(params);handleSuccess(res, 'approveReject');};/** 【战区内未确权-二级审批】驳回 */const twoReject = async () => {const {id,pkNo,instanceId,subInstanceId,} = formDataDs.current?.toData();const { approveOpinion } = rejectDataDs.current?.toData();const taskIdValue = await getTaskId(subInstanceId);const params: ApprovalParams = {id,pkNo,taskId: taskIdValue?.[0]?.taskId,subInstanceId,instanceId,approveOpinion,approveResult: 'N',};const res = await postApprove(params);handleSuccess(res, 'approveReject');};/** 【战区内已确权-二级审批-一致】驳回 */const fourReject = async () => {const {id,pkNo,instanceId,subInstanceId,} = formDataDs.current?.toData();const { approveOpinion } = rejectDataDs.current?.toData();const taskIdValue = await getTaskId(subInstanceId);const params: ApprovalParams = {id,pkNo,taskId: taskIdValue?.[0]?.taskId,subInstanceId,instanceId,approveOpinion,approveResult: 'N',};const res = await postApprove(params);handleSuccess(res, 'approveReject');};/** 【跨战区-审批】:驳回 */const sevenReject = async () => {const {channelRemoveId,pkNo,subInstanceId,instanceId,} = formDataDs.current?.toData();const { approveOpinion } = rejectDataDs.current?.toData();const taskIdValue = await getTaskId(subInstanceId);const params: ApprovalParams = {id: channelRemoveId,pkNo,taskId: taskIdValue?.[0]?.taskId,subInstanceId,instanceId,approveOpinion,approveResult: 'N',};const res = await postApprove(params);handleSuccess(res, 'approveReject');};/** 公共:回调 */const handleSuccess = (res: any, kind: string) => {setLoading(false);if (res === '操作成功!') {message.success(res, undefined, undefined, 'top');modal.close();handleCancel();history.replace(`${pubPath}/success?from=${kind}`);} else {message.warning(res.message, undefined, undefined, 'top');}};return <></>;
};export default RejectModel;