### Install Pro Table Source: https://umijs.org/docs/max/charts Install the Pro Table component using pnpm. ```bash # 引入高级表格 pnpm install @ant-design/pro-table ``` -------------------------------- ### Install Pro List Source: https://umijs.org/docs/max/charts Install the Pro List component using pnpm. ```bash # 引入高级列表 pnpm install @ant-design/pro-list ``` -------------------------------- ### Check UmiJS Version Source: https://umijs.org/docs/api/commands Display the installed UmiJS version using the `umi version` command. This is equivalent to running `umi -v`. ```bash $ umi version 4.0.0 ``` -------------------------------- ### UmiJS v3 vs v4 GET Parameter Serialization Source: https://umijs.org/docs/max/request Compares the default GET parameter serialization behavior between UmiJS v3 and v4. UmiJS v3 uses the same key for array serialization, while UmiJS v4 (based on axios) uses brackets `[]` by default. ```tsx // Umi@3 import { useRequest } from 'umi'; // a: [1,2,3] => a=1&a=2&a=3 // Umi@4 import { useRequest } from '@umijs/max'; // a: [1,2,3] => a[]=1&a[]=2&a[]=3 ``` -------------------------------- ### Customizing GET Parameter Serialization in UmiJS v4 Source: https://umijs.org/docs/max/request Provides a solution to maintain UmiJS v3's array parameter serialization format (without brackets) in UmiJS v4 by configuring the `paramsSerializer` option with the `query-string` library. ```ts // src/app.[ts|tsx] /** @doc https://github.com/sindresorhus/query-string#arrayformat-1 */ + import queryString from 'query-string'; export const request: RequestConfig = { + paramsSerializer(params) { + return queryString.stringify(params); + }, ... } ``` -------------------------------- ### Get All Available Locales Source: https://umijs.org/docs/max/i18n Retrieve an array of all available locale keys, including those added dynamically via `addLocale`. This function by default looks for locale files in `src/locales`. ```typescript import { getAllLocales } from 'umi'; getAllLocales(); // [en-US, zh-CN, ...] ``` -------------------------------- ### Get Current Locale Source: https://umijs.org/docs/max/i18n Retrieve the currently selected locale key using the `getLocale()` interface. ```typescript import { getLocale } from 'umi'; getLocale(); // zh-CN ``` -------------------------------- ### Unified Imports from Umi Source: https://umijs.org/docs/introduce/philosophy Demonstrates how to import various functionalities and utilities directly from 'umi', simplifying dependency management and reducing import statements in your code. This approach is beneficial for managing a large number of plugins and their exported features. ```typescript // 大量插件为 umi 提供额外导出内容 import { connect, useModel, useIntl, useRequest, MicroApp, ... } from 'umi'; ``` -------------------------------- ### View MFSU Dependency Information Source: https://umijs.org/docs/api/commands Use the `umi mfsu` command to view MFSU dependency information. This command lists the dependencies managed by MFSU. ```bash $ umi mfsu warning@4.0.3 regenerator-runtime/runtime.js@0.13.11 react/jsx-dev-runtime@18.1.0 react-intl@3.12.1 react-error-overlay/lib/index.js@6.0.9 react@18.1.0 qiankun@2.8.4 lodash/noop@4.17.21 lodash/mergeWith@4.17.21 lodash/concat@4.17.21 ... ``` -------------------------------- ### Configure Husky for Commit Message Verification Source: https://umijs.org/docs/api/commands Integrate `umi verify-commit` with Husky by configuring the `.husky/commit-msg` file. This ensures commit messages adhere to specified standards. ```bash #!/bin/sh . "$(dirname "$0")/_/husky.sh" npx --no-install umi verify-commit $1 ``` -------------------------------- ### Build MFSU Dependencies Source: https://umijs.org/docs/api/commands Execute `umi mfsu build` to rebuild MFSU dependencies. This is useful when MFSU cache is missing or dependency information has changed. ```bash $ umi mfsu build info - Preparing... info - MFSU eager strategy enabled warn - Invalidate webpack cache since mfsu cache is missing info - [MFSU] buildDeps since cacheDependency has changed ... info - [plugin: @umijs/preset-umi/dist/commands/mfsu/mfsu] [MFSU][eager] build success ``` -------------------------------- ### Prepare Test Data Source: https://umijs.org/docs/max/charts Provides an array of Test objects, each with an id, name, image URL, and description. ```typescript const testList: Test[] = [ { id: 9903, name: '语雀的天空', image: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg', desc: '覆盖了登录模块的所有测试用例', }, { id: 9904, name: 'Ant Design', image: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg', desc: '覆盖了所有测试用例,所有的案例均已在 Node 17 测试环境验证完成', }, { id: 9905, name: '蚂蚁集团体验科技', image: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg', desc: '覆盖了所有测试需求,所有的案例均已在 Ubuntu 14.04 测试环境验证完成', }, { id: 9906, name: 'TechUI', image: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg', desc: '覆盖了所有测试需求,所有的案例均已在 MacOS 测试环境验证完成', }, ]; ``` -------------------------------- ### Define Global Initial State Source: https://umijs.org/docs/max/data-flow Define the `getInitialState` function in `src/app.ts` to fetch and return initial data for your Umi project. This data will be available globally. ```typescript // src/app.ts import { fetchInitialData } from '@/services/initial'; export async function getInitialState() { const initialData = await fetchInitialData(); return initialData; } ``` -------------------------------- ### Umi Request v3 to v4 Configuration Migration Source: https://umijs.org/docs/max/request Shows the differences in runtime configuration between UmiJS v3 and v4, specifically highlighting the shift from umi-request to axios and the changes in error handling and interceptors. ```diff export const request: RequestConfig = { errorConfig: { ++ errorHandler: () => {}, ++ errorThrower: () => {} -- errorPage: '', -- adaptor: ()=> {}, }; -- middlewares: [], ++ requestInterceptors: [], ++ responseInterceptors: [], ... // umi-request 和 axios 的区别。 }; ``` -------------------------------- ### Prepare Member Data Source: https://umijs.org/docs/max/charts Prepares an array of Member objects by combining predefined arrays of names, emails, and phones. ```typescript const realNames = ['马巴巴', '张三丰', '飞蓬', '徐长卿']; const nickNames = ['巴巴', '君宝', '景天', '姓徐的']; const emails = ['baba@antfin.com', 'junbao@antfin.com', 'jingtian@antfin.com', 'xvzhangmen@antfin.com']; const phones = ['18800001234', '13900002345', '17200003456', '17800004567']; const memberList: Member[] = []; for (let i = 0; i < realNames.length; i++) { memberList.push({ id: `${102047 + i}`, realName: realNames[i], nickName: nickNames[i], email: emails[i], phone: phones[i], }); } ``` -------------------------------- ### Pro List with Test Data Source: https://umijs.org/docs/max/charts Renders a Pro List with test results, displaying title, image, description, and actions (link, warning, view). Includes a toolbar with an 'Add' button. ```tsx import React from 'react'; import { Button } from 'antd'; import ProList from '@ant-design/pro-list'; // resolve test info list const MemberList: React.FC = () => { return ( toolBarRender={() => { return [ , ]; }} rowKey="id" headerTitle="测试结果" dataSource={testList} showActions="hover" showExtra="hover" metas={{ title: { dataIndex: 'name', }, avatar: { dataIndex: 'image', }, description: { dataIndex: 'desc', }, actions: { render: (text, row) => [ 链路, 报警, 查看, ], }, }} /> ); } ``` -------------------------------- ### Migrating Middleware to Interceptors Source: https://umijs.org/docs/max/request Illustrates how to replace UmiJS v3 middleware functionality with v4's request and response interceptors. Logic before 'next()' in middleware goes into requestInterceptors, and logic after 'next()' goes into responseInterceptors. ```ts // 中间件 async function middleware(ctx, next) { const { url, options } = req; if (url.indexOf('/api') !== 0) { ctx.req.url = `/api/v1/${url}`; } await next(); if (!ctx.res.success) { // do something } } // 拦截器 { requestInterceptors:[ (config) => { if (config.url.indexOf('/api') !== 0) { config.url = `/api/v1/${url}`; } return config; } ], responseInterceptors: [ (response) => { if(!response.data.success){ // do something } } ] } ``` -------------------------------- ### Custom React-intl Initialization Options Source: https://umijs.org/docs/max/i18n Configure additional `react-intl` initialization options in `src/app.ts` for advanced customization. This allows setting properties like `onError`, `textComponent`, etc. ```typescript // src/app.ts import { RuntimeConfig } from '@umijs/max' export const locale: RuntimeConfig['locale'] = { textComponent: 'span', onError: () => { console.log('error handler...'); } // locale: string // formats: CustomFormats // messages: Record | Record // defaultLocale: string // defaultFormats: CustomFormats // timeZone?: string // textComponent?: React.ComponentType | keyof React.ReactHTML // wrapRichTextChunksInFragment?: boolean // defaultRichTextElements?: Record> // onError(err: string): void } ``` -------------------------------- ### Format Messages with useIntl Source: https://umijs.org/docs/max/i18n Obtain the `intl` object using the `useIntl` hook to format messages with dynamic values. This is the recommended way to handle internationalized messages in components. ```json // src/locales/en-US.json { "welcome": "Hi, {name}." } ``` ```typescript import { useIntl } from 'umi'; const intl = useIntl(); const msg = intl.formatMessage( { id: 'welcome', }, { name: 'Jackson', }, ); console.log(msg); // Hi, Jackson. ``` -------------------------------- ### Configure Internationalization Plugin Source: https://umijs.org/docs/max/i18n Configure the internationalization plugin in `.umirc.ts`. Options include enabling antd support, browser language detection, locale separators, default locale, and title internationalization. ```typescript export default { locale: { antd: false, // 如果项目依赖中包含 `antd`,则默认为 true baseNavigator: true, baseSeparator: '-', default: 'zh-CN', title: false, useLocalStorage: true, }, }; ``` -------------------------------- ### Dynamically Add Locale Support Source: https://umijs.org/docs/max/i18n Use `addLocale` to dynamically add language support at runtime without creating separate locale files. It accepts the locale key, a message object, and configuration options for moment and antd. ```typescript import { addLocale } from 'umi'; import zhTW from 'antd/es/locale/zh_TW'; addLocale( 'zh-TW', { welcome: '歡迎光臨 Umi 的世界!', }, { momentLocale: 'zh-tw', antd: zhTW, }, ); ``` -------------------------------- ### Access Global Initial State in Components Source: https://umijs.org/docs/max/data-flow Use the `useModel('@@initialState')` hook in your components to access the globally defined initial state, loading status, errors, and functions to refresh or set the state. ```typescript import { useModel } from 'umi'; export default function Page() { const { initialState, loading, error, refresh, setInitialState } = useModel('@@initialState'); return <>{initialState}; }; ``` -------------------------------- ### Remove MFSU Dependencies Source: https://umijs.org/docs/api/commands Use `umi mfsu remove` to clear MFSU dependency information. The `--all` flag also removes generated artifact files. ```bash $ # 删除依赖信息列表 $ umi mfsu remove $ # 删除依赖信息列表和产物文件 $ umi mfsu remove --all ``` -------------------------------- ### Pro Table with Member Data Source: https://umijs.org/docs/max/charts Renders a Pro Table with member data, including columns for name, nickname, account, phone, and actions (edit, remove). ```tsx import React from 'react'; import type { ProColumns } from '@ant-design/pro-table'; import ProTable from '@ant-design/pro-table'; // resolve member info list const MemberList: React.FC = () => { const columns: ProColumns[] = [ { dataIndex: 'realName', title: '姓名', }, { dataIndex: 'nickName', title: '昵称', }, { dataIndex: 'email', title: '账号', }, { dataIndex: 'phone', title: '手机号', }, { title: '操作', dataIndex: 'x', valueType: 'option', render: (_, record) => { return [编辑, 移除]; }, }, ]; return ( columns={columns} request={(params, sorter, filter) => { console.log(params, sorter, filter); return Promise.resolve({ data: memberList, success: true, }); }} rowKey="id" pagination={{ showQuickJumper: true, }} toolBarRender={false} search={false} /> ); } ``` -------------------------------- ### Cancel Request with AbortController Source: https://umijs.org/docs/max/request Demonstrates how to cancel an ongoing request using the fetch API's AbortController. This is useful for preventing unnecessary network activity when a component unmounts or a user navigates away. ```tsx import { request } from '@umijs/max'; import { Button } from 'antd'; const controller = new AbortController(); const HomePage: React.FC = () => { const fetchData = async () => { const res = await request('/api/getData', { method: 'GET', signal: controller.signal }) } const cancelData = () => { controller.abort(); } return ( <> ); }; export default HomePage; ``` -------------------------------- ### Enable Title Internationalization Source: https://umijs.org/docs/max/i18n Enable internationalized page titles by configuring the `title` option in `.umirc.ts` and adding `title` entries in your locale files. ```typescript // src/locales/zh-CN.ts export default { 'site.title': 'Umi - 企业级 React 应用开发框架', 'about.title': 'Umi - 关于我', }; ``` ```typescript // src/locales/en-US.ts export default { 'site.title': 'Umi - Enterprise-level React Application Framework', 'about.title': 'Umi - About me', }; ``` ```typescript // .umirc.ts export default { title: 'site.title', routes: [ { path: '/', component: 'Index', }, { path: '/about', component: 'About', title: 'about.title', }, ], }; ``` -------------------------------- ### Define Test Type Source: https://umijs.org/docs/max/charts Defines the TypeScript type for a test object, including id, name, image, and description. ```typescript export type Test = { id: number; name: string; image: string; desc: string; }; ``` -------------------------------- ### Use useModel Hook for Specific Model Data Source: https://umijs.org/docs/max/data-flow Utilize the `useModel` hook to selectively access specific properties and methods from a model. This can help optimize component performance by only subscribing to necessary data. ```typescript // src/components/AdminInfo/index.tsx import { useModel } from 'umi'; export default function Page() { const { user, fetchUser } = useModel('adminModel', (model) => ({ user: model.admin, fetchUser: model.fetchAdmin, })); return <>hello; }; ``` -------------------------------- ### Custom getLocale Logic Source: https://umijs.org/docs/max/i18n Customize the `getLocale()` method in `src/app.ts` to implement custom logic for determining the current locale, such as parsing it from URL query parameters. ```typescript // src/app.ts import qs from 'qs'; export const locale = { getLocale() { const { search } = window.location; const { locale = 'zh-CN' } = qs.parse(search, { ignoreQueryPrefix: true }); return locale; }, }; ``` -------------------------------- ### Define Member Type Source: https://umijs.org/docs/max/charts Defines the TypeScript type for a member object, including id, realName, nickName, email, and phone. ```typescript export type Member = { id: number; realName: string; nickName: string; email: string; phone: string; }; ``` -------------------------------- ### Set Current Locale Programmatically Source: https://umijs.org/docs/max/i18n Use `setLocale` to programmatically change the current language. You can choose whether to reload the page upon switching languages. ```typescript import { setLocale } from 'umi'; // 切换时刷新页面 setLocale('en-US'); // 切换时不刷新页面 setLocale('en-US', false); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.