Browse Source

feat: querystring refactor to URLSearchParams

lanjianrong 4 years atrás
parent
commit
31d34dbe8c

+ 0 - 3
.prettierrc.js

@@ -1,7 +1,4 @@
-const fabric = require('@umijs/fabric')
-
 module.exports = {
-  ...fabric.prettier,
   semi: false,
   // quoteProps: 'consistent',
   htmlWhitespaceSensitivity: 'ignore',

+ 1 - 3
config/config.js

@@ -33,11 +33,9 @@ export default defineConfig({
     baseNavigator: false
   },
   define: { REACT_APP_ENV: REACT_APP_ENV || false },
-  history: { type: 'browser' },
   targets: { ie: 11 },
   routes,
   title: false,
-  ignoreMomentLocale: true,
   proxy: proxy[REACT_APP_ENV || 'dev'],
   manifest: { basePath: '/' },
   extraBabelPlugins: [
@@ -66,7 +64,7 @@ export default defineConfig({
       : [
           'https://d2.smartcost.com.cn/cach/cld/react18.1.0/react.production.min.js',
           'https://d2.smartcost.com.cn/cach/cld/react18.1.0/react-dom.production.min.js'
-        ],
+        ]
   // chainWebpack(config, { env }) {
   //   config.plugin('windicss').use('windicss-webpack-plugin')
   //   config.plugin('moment2dayjs').use('antd-dayjs-webpack-plugin')

+ 3 - 2
package.json

@@ -45,6 +45,7 @@
     "moment": "^2.29.3",
     "omit.js": "^2.0.2",
     "qs": "^6.9.4",
+    "querystring": "^0.2.1",
     "rc-util": "^5.16.1",
     "rc-virtual-list": "^3.4.8",
     "react": "18.1.0",
@@ -70,11 +71,11 @@
     "babel-plugin-import": "^1.13.5",
     "cross-env": "^7.0.0",
     "eslint": "^8.17.0",
+    "husky": "^8.0.0",
     "lint-staged": "^10.0.0",
     "prettier": "^2.6.1",
     "stylelint": "^14.9.0",
-    "typescript": "^4.7.3",
-    "husky": "^8.0.0"
+    "typescript": "^4.7.3"
   },
   "engines": {
     "node": ">=10.0.0"

+ 1 - 1
src/access.ts

@@ -9,7 +9,7 @@ export default function (initialState) {
       return true
     }
     const name = route.path?.match(/\/(\w*)\//)?.[1]
-    console.log(route)
+    // console.log(route)
 
     if (name && permData[name] && permData[name]?.length) {
       return true

+ 17 - 8
src/app.tsx

@@ -80,9 +80,7 @@ export const layout = ({ initialState, setInitialState }) => {
       if (!initialState?.currentUser?.staffId && location.pathname !== loginPath) {
         history.replace({
           pathname: loginPath,
-          search: stringify({
-            redirect: history.location.pathname
-          })
+          search: new URLSearchParams({ redirect: window.location.pathname }).toString()
         })
       } else {
         location.pathname !== loginPath &&
@@ -104,9 +102,7 @@ const errorHandler = error => {
     if (consts.TOKEN_INVALID_CODE.includes(errorCode) && window.location.pathname !== loginPath) {
       history.replace({
         pathname: loginPath,
-        search: stringify({
-          redirect: window.location.pathname
-        })
+        search: new URLSearchParams({ redirect: window.location.pathname }).toString()
       })
     }
     switch (showType) {
@@ -154,7 +150,19 @@ const authHeaderInterceptor = (url, options) => {
 }
 
 export const request: RequestConfig = {
-  errorHandler,
+  errorConfig: {
+    // 错误抛出
+    errorThrower: (res: ResponseStructure) => {
+      const { data, code, msg, showType } = res
+      if (code !== consts.RET_CODE.SUCCESS) {
+        const error: any = new Error(errorMessage)
+        error.name = 'BizError'
+        error.info = { errorCode: code, errorMessage: msg, showType, data }
+        throw error // 抛出自制的错误
+      }
+    },
+    errorHandler
+  },
   baseURL: consts.PREFIX_URL,
   // 默认错误处理
   credentials: 'include', // 默认请求是否带上cookie
@@ -172,5 +180,6 @@ export const request: RequestConfig = {
       }
     }
   },
-  requestInterceptors: [authHeaderInterceptor]
+  requestInterceptors: [authHeaderInterceptor],
+  responseInterceptors: []
 }

+ 4 - 9
src/components/RightContent/AvatarDropdown.tsx

@@ -2,7 +2,7 @@
 import React, { useCallback } from 'react'
 import { InfoCircleFilled, LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons'
 import { Avatar, Menu, Spin, Modal } from 'antd'
-import { history, useModel } from '@umijs/max'
+import { createSearchParams, history, useModel } from '@umijs/max'
 import { stringify } from 'querystring'
 import HeaderDropdown from '../HeaderDropdown'
 import styles from './index.less'
@@ -19,24 +19,19 @@ export type GlobalHeaderRightProps = {
  * 退出登录,并且将当前的 url 保存
  */
 const loginOut = async () => {
-  const { query = {}, pathname } = history.location
-  const { redirect } = query
   // Note: There may be security issues, please note
-  if (window.location.pathname !== '/user/login' && !redirect) {
+  if (window.location.pathname !== consts.LOGIN_PATH) {
     // 断开socket连接
     ws.disconnect()
     history.replace({
       pathname: '/user/login',
-      search: stringify({
-        redirect: pathname
-      })
+      search: createSearchParams({ redirect: window.location.pathname }).toString()
     })
   }
 }
 
 const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
   const { initialState, setInitialState } = useModel('@@initialState')
-
   const onMenuClick = useCallback(
     (event: {
       key: React.Key
@@ -96,7 +91,7 @@ const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
   )
 
   return (
-    <HeaderDropdown overlay={menuHeaderDropdown}>
+    <HeaderDropdown overlay={menuHeaderDropdown} destroyPopupOnHide>
       <span className={`${styles.action} ${styles.account}`}>
         <Avatar
           size="small"

+ 1 - 11
src/components/Table/src/BasicTable.tsx

@@ -79,8 +79,6 @@ const BasicTable: {
   })
 
   useUpdateLayoutEffect(() => {
-      console.log('111', state.dataSource)
-
       state.dataSource && redoHeight(state.dataSource)
   }, [state.dataSource])
 
@@ -132,8 +130,6 @@ const BasicTable: {
       return {
         ...rowSelection,
         onChange: selectedRowKeys => {
-          console.log(selectedRowKeys)
-
           rowOnChange(selectedRowKeys)
           setState({ ...state, selectKeysRef: selectedRowKeys })
         }
@@ -141,11 +137,7 @@ const BasicTable: {
     }
     return {
       ...rowSelection,
-      onChange: selectedRowKeys => {
-        console.log(selectedRowKeys)
-
-        setState({ ...state, selectKeysRef: selectedRowKeys })
-      }
+      onChange: selectedRowKeys => setState({ ...state, selectKeysRef: selectedRowKeys })
     }
   }, [rowSelection])
 
@@ -165,11 +157,9 @@ const BasicTable: {
   )
 
   const _onLoad = useMemoizedFn(_dataSource => {
-
     onLoad?.(_dataSource)
     // TODO: 使用[request]api才对dataSource进行赋值, 规避掉手动设置[dataSource] api 自适应高度失效
     if (!isUnDef(request)) {
-      console.log('11', _dataSource)
       setState({ ...state, dataSource: _dataSource })
     }
     // TODO: 手动设置数据源的情况进行自适应宽高调整

+ 11 - 7
src/global.less

@@ -1,3 +1,6 @@
+/* stylelint-disable property-no-vendor-prefix */
+/* stylelint-disable selector-pseudo-element-colon-notation */
+/* stylelint-disable selector-class-pattern */
 @import '~antd/es/style/themes/default.less';
 html,
 body,
@@ -63,7 +66,7 @@ body,
 .ant-btn-primary[disabled]:focus,
 .ant-btn-primary[disabled]:active {
   color: white;
-  background: rgba(136, 106, 181, 0.5);
+  background: rgba(136 106 181 / 50%);
 }
 
 .ant-pro-top-nav-header-logo h1 {
@@ -75,7 +78,7 @@ canvas {
 }
 
 body {
-  text-rendering: optimizeLegibility;
+  text-rendering: optimizelegibility;
   -webkit-font-smoothing: antialiased;
   -moz-osx-font-smoothing: grayscale;
 }
@@ -87,8 +90,9 @@ ol {
   padding: 0;
 }
 
-/* stylelint-disable-next-line selector-pseudo-element-colon-notation */
-*, :after, :before {
+*,
+:after,
+:before {
   box-sizing: border-box;
   border: 0 solid #e4e4e7;
 }
@@ -140,7 +144,6 @@ input:-webkit-autofill:active {
   width: 100% !important;
 }
 
-
 // 弹窗左右结构
 .sheet-box {
   // overflow: hidden;
@@ -171,7 +174,8 @@ input:-webkit-autofill:active {
       height: 54px;
     }
     .sheet-right-panel {
-      & .ant-card, & .ant-table {
+      & .ant-card,
+      & .ant-table {
         background: #fafafa;
       }
       // 空数据时tbody样式
@@ -195,7 +199,7 @@ input:-webkit-autofill:active {
   height: 8px;
 }
 ::-webkit-scrollbar-track {
-  background: rgb(239, 239, 239);
+  background: rgb(239 239 239);
   border-radius: 2px;
 }
 ::-webkit-scrollbar-thumb {

+ 14 - 14
src/pages/User/Login/index.tsx

@@ -1,9 +1,8 @@
 import { LockOutlined, UserOutlined } from '@ant-design/icons'
 import { Alert, notification, Tabs } from 'antd'
-import React, { useState } from 'react'
+import React, { useState, useTransition } from 'react'
 import ProForm, { ProFormCheckbox, ProFormText } from '@ant-design/pro-form'
-import { useIntl, history, FormattedMessage, useModel } from '@umijs/max'
-
+import { useIntl, history, FormattedMessage, useModel, createSearchParams } from '@umijs/max'
 import styles from './index.less'
 import { apiLogin } from '@/services/login'
 import { setAuthCache } from '@/utils/auth'
@@ -11,7 +10,7 @@ import { TOKEN_KEY } from '@/utils/cache/cacheEnum'
 import { DEFAULT_CACHE_TIME } from '@/settings/encryptionSetting'
 import consts from '@/consts'
 import { isUnDef } from '@/utils/is'
-
+import 'antd/lib/notification/style'
 const LoginMessage = ({ content }) => (
   <Alert
     style={{
@@ -29,8 +28,8 @@ const Login = () => {
     status: '',
     type: 'account'
   })
+  const [, startTransition] = useTransition()
   const { initialState, setInitialState } = useModel('@@initialState')
-
   const intl = useIntl()
 
   const fetchUserInfo = async () => {
@@ -45,17 +44,18 @@ const Login = () => {
   /** 此方法会跳转到 redirect 参数所在的位置 */
   const goto = username => {
     if (!history) return
-    const searchParams = new URLSearchParams(history.location.search)
+    const searchParams = createSearchParams(window.location.search)
     const redirect = searchParams.get('redirect')
-    console.log(redirect)
-    // 清除所有notification
-    notification.destroy()
-    notification.success({
-      message: intl.formatMessage({ id: 'pages.login.success.title' }),
-      description: redirect && `${intl.formatMessage({ id: 'pages.login.success.desc' })}: ${username}`,
-      duration: 3
+    startTransition(() => {
+      // 清除所有notification
+      notification.destroy()
+      notification.success({
+        message: intl.formatMessage({ id: 'pages.login.success.title' }),
+        description: redirect && `${intl.formatMessage({ id: 'pages.login.success.desc' })}: ${username}`,
+        duration: 3
+      })
     })
-    return history.replace(redirect || '/')
+    history.replace(redirect || '/')
   }
 
   const handleSubmit = async values => {