一、安装及完整区块、运行、打包命令
API:
V5版:https://beta-pro.ant.design/index-cn
ProTable:https://protable.ant.design/getting-started
ProComponents:https://procomponents.ant.design/docs/intro/
Hooks:https://hooks.umijs.org/zh-CN/hooks/async
安装:yarn create umi [项目名]
运行:yarn run start
打包:umi build
安装完整区块(如官网方法无法安装,使用本地安装):
• 1、自己手动下载https://github.com/ant-design/pro-blocks所有区块
• 2、将下载的文件解压拷贝到C:/Users/用户名/.umi/blocks/github.com/ant-design/pro-blocks文件夹下,没有就自己建文件夹。
• 3、在工程目录执行 yarn run pro fetch-blocks --branch=v5
二、使请求携带Token
**src/app.tsx文件修改**
export const request: RequestConfig = {
errorHandler,
headers: {
Authorization: `${localStorage.getItem(token)}`,
},
};
**service.ts文件中使用**
import { request } from 'umi';
export async function querySchedule(params: any) {
return request('/edu/querySchedule', { params });
}
坑:V5官方代码Login组件,登录后发现请求仍不能携带token,问题在于登录后使用了history跳转,倒致一些问题。
//**src/pages/user/Login/index.tsx**
/** 此方法会跳转到 redirect 参数所在的位置 */
const goto = () => {
if (!history) return;
setTimeout(() => {
const { query } = history.location;
const { redirect } = query as { redirect: string };
history.push(redirect || '/');
}, 10);
};
可以改为
/** 登录后跳转到 redirect参数所在的位置 */
export const goto = (path: string) => {
const { query } = history.location;
const { redirect } = query as { redirect: string };
window.location.href = redirect || path;
};
调用: goto('/');
三、关于currentUser
对于每个页面都要使用的全局信息,如用户信息currentUser,可在src/app.tsx中设置,任何页面打开自动请求。
import useRequest from '@ahooksjs/use-request';
import ProTable from '@ant-design/pro-table';
export async function getInitialState(): Promise<{
settings?: Partial;
currentUser?: API.CurrentUser;
fetchUserInfo?: () => Promise;
}> {
const fetchUserInfo = async () => {
try {
const currentUser = await queryCurrentUser();
return currentUser.data;
} catch (error) {
history.push(loginPath);
}
return undefined;
};
const currentUser = await fetchUserInfo();
console.log(currentUser);
return {fetchUserInfo, currentUser,settings: {},};
}
**index.tsx组件中使用**
const { initialState } = useModel('@@initialState');
const currentUser = initialState?.currentUser;
return ( //就可直接使用了
<> {console.log(currentUser)}>
四、useModel使用问题
对于某些数据只在多个页面中使用但也需共享,使用useModel.建议使用useModel导出方法,不然打包后,打开网站主页便会请求所有useModel内容。
**src/models/inner.ts** 没有文件夹就新建
import { useRequest } from '@umijs/hooks';
import { queryTeacher } from '@/pages/inner/finance/service';
export default () => {
const fetchTeacher= () => {
const teachers: any = useRequest(queryTeacher).data?.data;
}
return {fetchTeacher,};
}
**在组件index.tsx中使用,'inner'为文件名,只有取值时,才会发送queryTeacher请求**
const { fetchTeacher } = useModel('inner');
const options = fetchTeacher();
五、access权限的使用方法:
**src/access.ts**
export default function access(initialState: { currentUser?: API.CurrentUser }) {
const { currentUser } = initialState || {};
const roles: any = currentUser?.roleList; //后端返回角色列表
const getRoles: any = (role: string) => {
for (let i in roles) {
if (role === roles[i]) {
return true;
}
}
return false;
};
let hasRoutes: any = ['inner','setting']; //可从后端返回,在app.tsx中全局携带, currentUser.hasRoutes取出,控制用户访问权限
return {
canRoot: currentUser && getRoles(root), //结果为true代表具有该角色权限
accessFilter: (route: any) => hasRoutes.includes(route.name),
};
}
**index.tsx组件中使用,如某个button需要root角色才能显示
import { Access, useAccess } from 'umi';
const access = useAccess();
return (
<>
>)
**config/routes.ts**
{
path: '/inner',
name: 'inner',
access: 'accessFilter', //代表hasRoutes数组里的角色都能访问该路由
//access: 'canRoot', //只有root角色才能访问该路由
routes: [...],
},
六、常见问题
1、完整请求例子,useState,useEffect,后端请求方法等
import useRequest from '@ahooksjs/use-request';
const finance: React.FC = () => {
const [dataSource, setDataSource] = useState();
//**页面加载自动请求后端,详见API Hooks
//**useRequest(queryData, {
//** onSuccess: (res: any, params) => {setDataSource(res.data); }});}
//手动方式,如表格新增项后须手动请求刷新数据。调用doGetData({})
const { run: doGetData } = useRequest(queryData, {
manual: true,
onSuccess: (res: any, params) => { setDataSource(res.data); }
});
useEffect(() => { doGetData ({}); }, []) //手动请求须写useEffect,[]代表进页面只请求一次
const columns = [
{ title: '序', dataIndex: 'index', valueType: 'indexBorder', width: 30, },
{
title: '时间', key: 'time', dataIndex: 'time', ellipsis: true, hideInSearch: true, //hideIntable: true,
}
]
return (
<> {
// return queryData({
// 如后端接收参名为size,可为样写size: params.pageSize,
// ...params, ...sort
// });}}
/>>)
}
export default finance;
**service.ts文件内容
import { request } from 'umi';
export async function queryData(params) {
return request('/queryData', {params,});
}
2、Form表单设置值与取值
import { Form } from 'antd';
export default (): React.ReactNode => {
const defaultValues = {type: "默认值1", mclass: "默认值2"};
const [ceshiForm] = Form.useForm();
const handleSubmit = (values:any) => {
console.log(values);
}
return (
handleSubmit(values)}
>
{ onChange: () => { ceshiForm.setFieldsValue({ mclass: '我是猪' }) } }}
/>
{ onChange: () => { console.log(ceshiForm.getFieldValue('type'))} }}
/>
评论列表(0条)