Browse Source

feat: 调整dva refresh更新逻辑

lanjianrong 4 years ago
parent
commit
2b31e8cce3

+ 46 - 45
src/components/ModalStore/src/CreateProvider.tsx

@@ -1,7 +1,9 @@
 import { message } from 'antd'
 import type { CSSProperties } from 'react'
+import { useState } from 'react'
 import React from 'react'
 import { ModalContext } from './context'
+import { useDispatch } from 'umi'
 export interface ModalFullConfig<T = any> {
   destroyOnClose?: boolean | string
   visiblePropName?: string
@@ -26,17 +28,14 @@ export interface ModalStoreState {
   currentModal: ModalItem[]
 }
 
-class ModalStore extends React.Component<ModalStoreProps, ModalStoreState> {
-  constructor(props: ModalStoreProps) {
-    super(props)
-    this.state = {
-      currentModal: []
-    }
-  }
-
+const ModalStore: React.FC<ModalStoreProps> = props => {
+  const dispatch = useDispatch()
+  const [state, setState] = useState<ModalStoreState>({
+    currentModal: []
+  })
   // 获取modal的config
-  private getModalConfig(key: string) {
-    const { modalMap = {}, visiblePropName = 'visible' } = this.props
+  function getModalConfig(key: string) {
+    const { modalMap = {}, visiblePropName = 'visible' } = props
     const componentKey = key.split('@')?.[0]
     let config = modalMap[componentKey]
     if (typeof config === 'function') config = { component: config }
@@ -50,14 +49,14 @@ class ModalStore extends React.Component<ModalStoreProps, ModalStoreState> {
     return { visiblePropName, onClosePropName, destroyOnClose, config }
   }
 
-  private setModalState(fn: (prev: ModalItem[]) => ModalItem[]) {
-    this.setState(prev => ({ currentModal: fn(prev.currentModal) }))
+  function setModalState(fn: (prev: ModalItem[]) => ModalItem[]) {
+    setState(prev => ({ currentModal: fn(prev.currentModal) }))
   }
 
-  private getCloseFunction(key: string, cb?: (...args: any[]) => void) {
+  function getCloseFunction(key: string, cb?: (...args: any[]) => void) {
     return (...args: any[]) => {
-      const { visiblePropName } = this.getModalConfig(key)
-      this.setModalState(prev => {
+      const { visiblePropName } = getModalConfig(key)
+      setModalState(prev => {
         return prev.map(item => {
           if (item.key === key) {
             return { ...item, [visiblePropName]: false }
@@ -71,37 +70,43 @@ class ModalStore extends React.Component<ModalStoreProps, ModalStoreState> {
     }
   }
 
-  private getDestroyFunction(key: string, cb?: (...args: any[]) => void) {
+  function getDestroyFunction(key: string, cb?: (...args: any[]) => void) {
     return (...args: any[]) => {
-      this.setModalState(prev => prev.filter(v => v.key !== key))
+      setModalState(prev => prev.filter(v => v.key !== key))
       if (typeof cb === 'function') {
         cb(...args)
       }
     }
   }
 
-  private push = (key: string, state: any) => {
+  function push(key: string, compState: any) {
+    console.log(compState)
+
     // eslint-disable-next-line no-param-reassign
-    key = state?.dataId ? `${key}@${state?.dataId}` : key
-    const { visiblePropName, onClosePropName, destroyOnClose } = this.getModalConfig(key)
+    key = compState?.dataId ? `${key}@${compState?.dataId}` : key
+    const { visiblePropName, onClosePropName, destroyOnClose } = getModalConfig(key)
 
-    this.setModalState(prevModals => {
+    setModalState(prevModals => {
       const defaultProps: any = {
         [visiblePropName]: key.startsWith('D') ? false : true,
-        [onClosePropName]: this.getCloseFunction(key, state?.[onClosePropName])
+        [onClosePropName]: getCloseFunction(key, compState?.[onClosePropName])
       }
-
+      compState?.dataId &&
+        dispatch({
+          type: 'refresh/commitAction',
+          payload: compState.dataId
+        })
       if (destroyOnClose) {
         const prop = typeof destroyOnClose === 'string' ? destroyOnClose : onClosePropName
 
         defaultProps[prop] =
           destroyOnClose === 'afterVisibleChange'
-            ? (visible: boolean) => !visible && this.getDestroyFunction(key)()
-            : this.getDestroyFunction(key)
+            ? (visible: boolean) => !visible && getDestroyFunction(key)()
+            : getDestroyFunction(key)
       }
 
       const newModal = {
-        ...state,
+        ...compState,
         ...defaultProps,
         key
       }
@@ -125,7 +130,7 @@ class ModalStore extends React.Component<ModalStoreProps, ModalStoreState> {
     if (key.startsWith('D')) {
       // 利用事件循环,先让dom元素渲染出来再使其展示动画(否则可能导致抽屉无动画直接出现)
       setTimeout(() => {
-        this.setModalState(prevModals =>
+        setModalState(prevModals =>
           prevModals.map(item => {
             if (item.key === key) {
               return { ...item, visible: true }
@@ -137,9 +142,9 @@ class ModalStore extends React.Component<ModalStoreProps, ModalStoreState> {
     }
   }
 
-  private renderModal = (item: ModalItem) => {
-    const { config } = this.getModalConfig(item.key)
-    const nodeProps = this.renderMaskProps(item)
+  function renderModal(item: ModalItem) {
+    const { config } = getModalConfig(item.key)
+    const nodeProps = renderMaskProps(item)
     if (config) {
       // 弹窗
       if ('component' in config) {
@@ -151,12 +156,10 @@ class ModalStore extends React.Component<ModalStoreProps, ModalStoreState> {
     return null
   }
 
-  private renderMaskProps = (item: ModalItem) => {
+  function renderMaskProps(item: ModalItem) {
     // 没有dataId 不是抽屉
     if (!item.dataId) return item
-    const drawerStore = this.state.currentModal
-      .filter(modal => modal.dataId)
-      .map(modal => modal.dataId)
+    const drawerStore = state.currentModal.filter(modal => modal.dataId).map(modal => modal.dataId)
     const len = drawerStore.length
     if (len === 1) return item
     // 抽屉至少2个
@@ -174,17 +177,15 @@ class ModalStore extends React.Component<ModalStoreProps, ModalStoreState> {
     }
     return item
   }
-  render() {
-    const { currentModal } = this.state
-    const { children } = this.props
-
-    return (
-      <ModalContext.Provider value={this.push}>
-        {children}
-        {currentModal.map(this.renderModal)}
-      </ModalContext.Provider>
-    )
-  }
+  const { currentModal } = state
+  const { children } = props
+
+  return (
+    <ModalContext.Provider value={push}>
+      {children}
+      {currentModal.map(renderModal)}
+    </ModalContext.Provider>
+  )
 }
 
 export default ModalStore

+ 9 - 2
src/models/refresh.js

@@ -1,3 +1,5 @@
+import { isObject, isUnDef } from '@/utils/is'
+
 export default {
   namespace: 'refresh',
   state: {
@@ -11,9 +13,7 @@ export default {
     cloud: false,
     personal: false
   },
-  // 用于处理异步操作和业务逻辑,由action触发,但不能修改state
   effects: {
-    //
     *commitAction({ payload }, { put }) {
       yield put({
         type: 'changState',
@@ -23,6 +23,13 @@ export default {
   },
   reducers: {
     changState(state, action) {
+      if (isObject(action.payload)) {
+        const { main, target } = action.payload
+        return { ...state, [main]: !state[main], [target]: !state[target] }
+      }
+      if (isUnDef(state[action.payload])) {
+        return { ...state, [action.payload]: false }
+      }
       return {
         ...state,
         [action.payload]: !state[action.payload]

+ 15 - 10
src/pages/Customer/Client/components/ClientDetail/Form.jsx

@@ -11,7 +11,7 @@ import {
   LabelModeType
 } from '@/pages/Customer/Company/components/PersonLabel/const'
 
-const ContanctForm = props => {
+const ClientForm = props => {
   const {
     client,
     personTagColorMap,
@@ -19,21 +19,20 @@ const ContanctForm = props => {
     teamTagColorMap,
     teamTags,
     dispatch,
-    updateKey,
+    updatePayload,
     filterTag = false
   } = props
   const changeCopInputData = {
     customerName: client.companyName,
     customerId: client.companyId,
     targetName: client.clientName,
-    dataId: client.id,
-    actionPayload: updateKey
+    dataId: client.id
   }
 
   const refreshClient = () => {
     dispatch({
       type: 'refresh/commitAction',
-      payload: updateKey
+      payload: updatePayload
     })
   }
 
@@ -78,7 +77,11 @@ const ContanctForm = props => {
         label: '单位名称',
         editCellType: 'custom',
         customCell: (
-          <ChangeCompanyInput dataSource={changeCopInputData} defaultValue={defaultCompanyValue} />
+          <ChangeCompanyInput
+            actionPayload={updatePayload}
+            dataSource={changeCopInputData}
+            defaultValue={defaultCompanyValue}
+          />
         ),
         span: 24
       },
@@ -170,7 +173,8 @@ const ContanctForm = props => {
                 tagType={TagTypeEnum.PERSONTAG}
                 tagColumn={TagDataTypeEnum.CLIENT}
                 checkCallBack={refreshClient}
-                modeType={LabelModeType.column}>
+                modeType={LabelModeType.column}
+              >
                 <Add theme="filled" size="20" fill="#868e96" className="cursor-pointer" />
               </PersonLabel>
             </div>
@@ -197,7 +201,8 @@ const ContanctForm = props => {
                 tagType={TagTypeEnum.TEAMTAG}
                 tagColumn={TagDataTypeEnum.CLIENT}
                 checkCallBack={refreshClient}
-                modeType={LabelModeType.column}>
+                modeType={LabelModeType.column}
+              >
                 <Add theme="filled" size="20" fill="#868e96" className="cursor-pointer" />
               </PersonLabel>
             </div>
@@ -256,7 +261,7 @@ const ContanctForm = props => {
         dataSource={client}
         columns={columns}
         tartgetUrl="/client/update"
-        type={updateKey}
+        type={updatePayload}
       />
     </div>
   )
@@ -267,4 +272,4 @@ export default connect(({ client }) => ({
   personTags: client.personTags,
   teamTagColorMap: client.teamTagColorMap,
   teamTags: client.teamTags
-}))(ContanctForm)
+}))(ClientForm)

+ 2 - 2
src/pages/Customer/Client/components/ClientDetail/LowerList.jsx

@@ -9,7 +9,7 @@ export const servicelogEnum = {
   4: '在线服务'
 }
 
-const ContanctLowerList = props => {
+const ClientLowerList = props => {
   const {
     log: { log: logs = [] },
     servicelist
@@ -65,4 +65,4 @@ const ContanctLowerList = props => {
   )
 }
 
-export default ContanctLowerList
+export default ClientLowerList

+ 3 - 16
src/pages/Customer/Client/components/ClientDetail/TabList.jsx

@@ -10,7 +10,7 @@ import { ProductLabel } from '@/pages/Product/Lock/LockStore/index'
 import { useModal } from '@/components/ModalStore'
 import { Plus } from '@icon-park/react'
 
-const ContanctTabList = ({ clientId, software }) => {
+const ClientTabList = ({ clientId, software, updatePayload }) => {
   const { Text } = Typography
   const dispatch = useDispatch()
   const dispatchModal = useModal()
@@ -131,7 +131,7 @@ const ContanctTabList = ({ clientId, software }) => {
     // 刷新数据
     dispatch({
       type: 'refresh/commitAction',
-      payload: 'client'
+      payload: updatePayload
     })
     return code === consts.RET_CODE.SUCCESS
   }
@@ -142,17 +142,7 @@ const ContanctTabList = ({ clientId, software }) => {
   return (
     <div>
       <div className="pl-15px">
-        {/* <Tabs onChange={callback} type="card"> */}
         <Tabs>
-          {/* <TabPane tab="养护云造价" key="养护云造价">
-            <div className="sheet-right-panel">
-              养护云造价
-              <Table columns={curingcolumns} dataSource={curinglist} pagination={false} />
-            </div>
-          </TabPane>
-          <TabPane tab="大司空云计价" key="大司空云计价">
-            <div className="sheet-right-panel">大司空云计价</div>
-          </TabPane> */}
           <TabPane tab={<span>软件锁{renderBadge(software.total, true)}</span>} key="软件锁">
             <div className="sheet-right-panel">
               <ProTable
@@ -168,9 +158,6 @@ const ContanctTabList = ({ clientId, software }) => {
               />
             </div>
           </TabPane>
-          {/* <TabPane tab="通行账号" key="通行账号">
-            <div className="sheet-right-panel">通行账号</div>
-          </TabPane> */}
         </Tabs>
       </div>
       <div className="sheet-btns pl-15px pt-15px :not-first:ml-1">
@@ -188,4 +175,4 @@ const ContanctTabList = ({ clientId, software }) => {
   )
 }
 
-export default ContanctTabList
+export default ClientTabList

+ 18 - 12
src/pages/Customer/Client/components/ClientDetail/index.jsx

@@ -1,9 +1,9 @@
 import { Row, Col, Spin, Tooltip, Drawer } from 'antd'
 import React, { useState, useEffect } from 'react'
-import ContanctForm from './Form.jsx'
-import ContanctTabList from './TabList.jsx'
-import ContanctLowerList from './LowerList.jsx'
-import { apiContactDetail } from '@/services/customer'
+import ClientForm from './Form.jsx'
+import ClientTabList from './TabList.jsx'
+import ClientLowerList from './LowerList.jsx'
+import { apiClientDetail } from '@/services/customer'
 import consts from '@/consts'
 import { connect } from 'umi'
 import { Up, Down } from '@icon-park/react'
@@ -15,11 +15,11 @@ const ClientDetail = props => {
     visible,
     dispatch,
     updateKey = 'client',
-    dataId = '',
+    dataId,
     orderIds = [],
     ...resetDrawerProps
   } = props
-  const shouldUpdate = refresh?.[updateKey] || false
+  const shouldUpdate = refresh?.[dataId ?? updateKey] || false
   const [state, setState] = useState({
     loading: false,
     client: {},
@@ -33,12 +33,15 @@ const ClientDetail = props => {
     const {
       data: { client = {}, log = [], serviceLog = [], software = {} },
       code = -1
-    } = await apiContactDetail(id)
+    } = await apiClientDetail(id)
     if (code === consts.RET_CODE.SUCCESS) {
       if (shouldUpdate) {
         dispatch({
           type: 'refresh/commitAction',
-          payload: 'client'
+          payload: {
+            main: updateKey,
+            target: dataId
+          }
         })
       }
       setState({ ...state, client, log, serviceLog, software, loading: false })
@@ -94,7 +97,10 @@ const ClientDetail = props => {
                 </div>
               ) : null}
               <div className="sheet-left-panel pr-4">
-                <ContanctForm client={state.client} updateKey={updateKey} />
+                <ClientForm
+                  client={state.client}
+                  updatePayload={{ main: updateKey, target: dataId }}
+                />
               </div>
             </Col>
             <Col
@@ -105,12 +111,12 @@ const ClientDetail = props => {
               // xl={{ span: 15 }}
               className="sheet-box-right"
             >
-              <ContanctTabList
+              <ClientTabList
                 clientId={state.client.id}
                 software={state.software}
-                updateKey={updateKey}
+                updatePayload={{ main: updateKey, target: dataId }}
               />
-              <ContanctLowerList log={state.log} servicelist={state.serviceLog} />
+              <ClientLowerList log={state.log} servicelist={state.serviceLog} />
             </Col>
           </Row>
         </div>

+ 0 - 2
src/pages/Customer/Client/index.jsx

@@ -17,12 +17,10 @@ import { generateFilterField, generateSortField } from '@/utils/utils'
 import { PermDataTypeEunm } from '../Company/components/PermSelect'
 import BasicTable from '@/components/Table'
 import { getPermAuthCache } from '@/utils/auth'
-// import FilterCascader from '@/components/Table/src/components/FilterCascader'
 import { useModal } from '@/components/ModalStore'
 import { Plus } from '@icon-park/react'
 const Client = props => {
   const dispatchModal = useModal()
-  // const { toggleDrawer, setDrawerProps } = useModal()
   const {
     personTagColorMap,
     teamTagColorMap,

+ 4 - 11
src/pages/Customer/Company/components/ChangeCompany/index.jsx

@@ -26,21 +26,14 @@ const ChangeCompanyInput = props => {
   const dispatch = useDispatch()
   const dispatchModal = useModal()
   const {
-    dataSource: {
-      customerId,
-      dataId,
-      customerName,
-      targetName,
-      actionPayload = ChangeCompMap.CLIENT.key,
-      title = '客户'
-    },
+    dataSource: { customerId, dataId, customerName, targetName, title = '客户' },
     defaultValue,
     showRemoveIcon = true,
     showConnectIcon = true,
-    editable = true
+    editable = true,
+    actionPayload = { main: ChangeCompMap.CLIENT.key }
   } = props
   const refreshClient = () => {
-    // console.log('actionPayload', actionPayload)
     dispatch({
       type: 'refresh/commitAction',
       payload: actionPayload
@@ -50,7 +43,7 @@ const ChangeCompanyInput = props => {
     dispatchModal('M_CONNECT_COMPANY', {
       onSelect: refreshClient,
       dataId,
-      preUrl: actionPayload,
+      preUrl: actionPayload.main,
       defaultAddibleValue: defaultValue
     })
   }

+ 7 - 5
src/pages/Customer/Company/components/CompanyDetail/Form.jsx

@@ -8,7 +8,7 @@ import { connect } from 'umi'
 
 const CompanyForm = props => {
   const {
-    updateKey,
+    updatePayload,
     customer,
     personTagColorMap,
     personTags,
@@ -35,7 +35,7 @@ const CompanyForm = props => {
   const refreshCompany = () => {
     dispatch({
       type: 'refresh/commitAction',
-      payload: 'company'
+      payload: updatePayload
     })
   }
 
@@ -127,7 +127,8 @@ const CompanyForm = props => {
             tagType={TagTypeEnum.PERSONTAG}
             tagColumn={TagDataTypeEnum.COMPANY}
             checkCallBack={refreshCompany}
-            modeType={LabelModeType.column}>
+            modeType={LabelModeType.column}
+          >
             <Add theme="filled" size="20" fill="#868e96" className="cursor-pointer" />
           </PersonLabel>
         </div>
@@ -154,7 +155,8 @@ const CompanyForm = props => {
             tagType={TagTypeEnum.TEAMTAG}
             tagColumn={TagDataTypeEnum.COMPANY}
             checkCallBack={refreshCompany}
-            modeType={LabelModeType.column}>
+            modeType={LabelModeType.column}
+          >
             <Add theme="filled" size="20" fill="#868e96" className="cursor-pointer" />
           </PersonLabel>
         </div>
@@ -180,7 +182,7 @@ const CompanyForm = props => {
         dataSource={customer}
         columns={columns}
         tartgetUrl="/customer/update"
-        type={updateKey}
+        type={updatePayload}
       />
     </div>
   )

+ 14 - 8
src/pages/Customer/Company/components/CompanyDetail/TabList.jsx

@@ -26,7 +26,7 @@ const CompanyTabList = ({
   software,
   customer,
   business,
-  updateKey
+  updatePayload
 }) => {
   const dispatch = useDispatch()
   const dispatchModal = useModal()
@@ -46,7 +46,7 @@ const CompanyTabList = ({
     if (code === consts.RET_CODE.SUCCESS) {
       dispatch({
         type: 'refresh/commitAction',
-        payload: updateKey
+        payload: updatePayload
       })
     }
   }
@@ -58,7 +58,8 @@ const CompanyTabList = ({
         if (key !== defaultSelectedKey) {
           changePriority(key, id)
         }
-      }}>
+      }}
+    >
       <Menu.Item key="1">1</Menu.Item>
       <Menu.Item key="2">2</Menu.Item>
       <Menu.Item key="3">3</Menu.Item>
@@ -80,7 +81,8 @@ const CompanyTabList = ({
         <Dropdown
           overlay={priorityMenu(text, record.id)}
           trigger="click"
-          className="hover:cursor-pointer">
+          className="hover:cursor-pointer"
+        >
           <span>
             {text} <DownOutlined />
           </span>
@@ -120,7 +122,8 @@ const CompanyTabList = ({
         <div className="text-primary hover:text-[#967bbd] line-clamp-1">
           <span
             onClick={() => dispatchModal('D_CLIENT_DETAIL', { dataId: record.id })}
-            className="cursor-pointer ">
+            className="cursor-pointer "
+          >
             {clientName}
           </span>
         </div>
@@ -167,7 +170,8 @@ const CompanyTabList = ({
           className={[
             'cursor-pointer hover:text-hex-967bbd',
             record.preserveStatus === 3 ? null : 'text-primary'
-          ].join(' ')}>
+          ].join(' ')}
+        >
           {record.preserveStatus === 3 ? (
             <Text delete type="secondary">
               {clientName}
@@ -256,7 +260,8 @@ const CompanyTabList = ({
       render: (text, record) => (
         <span
           onClick={() => dispatchModal('D_BUSINESS_DETAIL', { dataId: record.id })}
-          className="text-primary cursor-pointer hover:text-[#967bbd]">
+          className="text-primary cursor-pointer hover:text-[#967bbd]"
+        >
           {text}
         </span>
       )
@@ -380,7 +385,8 @@ const CompanyTabList = ({
                 landmarks: customer.landmarks
               }
             })
-          }>
+          }
+        >
           <Plus className="mr-1" />
           客户
         </Button>

+ 11 - 5
src/pages/Customer/Company/components/CompanyDetail/index.jsx

@@ -14,12 +14,12 @@ const CompanyDetail = props => {
     visible,
     dispatch,
     updateKey = 'company',
-    dataId = '',
+    dataId,
     orderIds = [],
     refresh,
     ...resetDrawerProps
   } = props
-  const shouldUpdate = refresh?.[updateKey] || false
+  const shouldUpdate = refresh?.[dataId ?? updateKey] || false
   const [state, setState] = useState({
     loading: false,
     customer: {},
@@ -46,7 +46,10 @@ const CompanyDetail = props => {
       if (shouldUpdate) {
         dispatch({
           type: 'refresh/commitAction',
-          payload: updateKey
+          payload: {
+            main: updateKey,
+            target: dataId
+          }
         })
       }
       setState({ ...state, customer, log, serviceLog, software, loading: false, client, business })
@@ -99,7 +102,10 @@ const CompanyDetail = props => {
               ) : null}
 
               <div className="sheet-left-panel pr-4">
-                <CompanyForm customer={state.customer} updateKey={updateKey} />
+                <CompanyForm
+                  customer={state.customer}
+                  updatePayload={{ main: updateKey, target: dataId }}
+                />
               </div>
             </Col>
             <Col
@@ -112,7 +118,7 @@ const CompanyDetail = props => {
               className="sheet-box-right"
             >
               <CompanyTabList
-                updateKey={updateKey}
+                updatePayload={{ main: updateKey, target: dataId }}
                 initData={initData}
                 customerId={flipConsts.curId}
                 software={state.software}

+ 12 - 1
src/pages/Product/Road/Enterprise/index.jsx

@@ -1,8 +1,19 @@
-import React from 'react'
+import { Button } from 'antd'
+import React, { useState, useEffect } from 'react'
 
 const Enterprise = () => {
+  const [state, setState] = useState({
+    a: {
+      b: 1
+    }
+  })
+  useEffect(() => {
+    console.log('1111')
+  }, [state.a])
+
   return (
     <div>
+      <Button onClick={() => setState({ ...state, a: { ...state.a.b, b: 2 } })}>111111</Button>
       <span>企业版</span>
     </div>
   )

+ 1 - 1
src/services/customer.js

@@ -100,7 +100,7 @@ export async function updateClient(payload) {
  * 获取客户详情
  * @param {string} id 客户记录id
  */
-export async function apiContactDetail(id) {
+export async function apiClientDetail(id) {
   const params = { id }
   return request('/client/detail', { params })
 }