在下载的脚手架中已经有调用接口实现与服务器的交互的例子了,我们以登录流程为例来进行讲解
1.在services层创建名为login的service,定义调用后端接口的方法


2.在model层创建名为login的model调用services中方法

import { stringify } from 'querystring';
import { router } from 'umi';
import { fakeAccountLogin, getFakeCaptcha } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
const Model = {
namespace: 'login',//命名空间,必须是唯一的名字
state: {
status: undefined,
},
effects: {
*login({ payload }, { call, put }) {
//调用services中的fakeAccountLogin函数
const response = yield call(fakeAccountLogin, payload);
yield put({
type: 'changeLoginStatus',
payload: response,
}); // Login successfully
if (response.code === 200) {
const urlParams = new URL(window.location.href);
const params = getPageQuery();
let { redirect } = params;
if (redirect) {
const redirectUrlParams = new URL(redirect);
if (redirectUrlParams.origin === urlParams.origin) {
redirect = redirect.substr(urlParams.origin.length);
if (redirect.match(/^\/.*#/)) {
redirect = redirect.substr(redirect.indexOf('#') + 1);
}
} else {
window.location.href = '/';
return;
}
}
router.replace(redirect || '/');
}
}
},
reducers: {//要想改变state中的数据,必须通过reducers,
//payload是参数
changeLoginStatus(state, { payload }) {
setAuthority(payload.currentAuthority);
return { ...state, status: payload.status, type: payload.type };
},
},
};
export default Model;
3.页面发起登录请求


‘login/login' 空间名/services中effect名
这样登录与后台交互功能就完成了

本文详细介绍了在Ant Design Pro项目中实现登录功能的具体步骤,包括创建登录服务、调用后端接口、状态管理及页面请求处理。通过具体代码示例,读者可以了解如何在实际项目中进行登录流程的开发。
188

被折叠的 条评论
为什么被折叠?



