Author:Mr.柳上原
- 付出不亚于任何的努力
- 愿我们所有的努力,都不会被生活辜负
- 不忘初心,方得始终
react里,请务必自己封装请求方法
承接上文 》》》
当自定义封装请求方法后,可以简化当前页面的后端数据请求代码
// 二次封装页面请求
/**
* 新增组件
* 调用接口方法 api
*/
import ApiClient, { callApi } from '@/utils/apiClient'; // 对接后端,公用接口验证
import { AuthorUrl } from '@/constants/baseConfig'; // 公用 url
const addApi = {
postOrganization: async (condition) => {
let url = `${AuthorUrl}/api/Organization`;
return await callApi(async () => {
return await ApiClient.post(url, condition);
})
}
}
export default addApi;
/**
* 删除组件
* 调用接口方法 api
*/
import ApiClient, { callApi } from '@/utils/apiClient'; // 对接后端,公用接口验证
import { AuthorUrl } from '@/constants/baseConfig'; // 公用 url
const deleteApi = {
delOrganization: async (organizationId) => {
let url = `${AuthorUrl}/api/Organization/${organizationId}`;
return await callApi(async () => {
return await ApiClient.del(url);
})
}
}
export default deleteApi;
/**
* 修改组件
* 调用接口方法 api
*/
import ApiClient, { callApi } from '@/utils/apiClient'; // 对接后端
import { AuthorUrl } from '@/constants/baseConfig'; // 公用 url
const editApi = {
putOrganization: async (organizationId, condition) => {
let url = `${AuthorUrl}/api/Organization/${organizationId}`;
return await callApi(async () => {
return await ApiClient.put(url, condition);
})
}
}
export default editApi;
/**
* 初始页面数据组件
* 调用接口方法 api
*/
import ApiClient, { callApi } from '@/utils/apiClient'; // 对接后端,公用接口验证
import { AuthorUrl } from '@/constants/baseConfig'; // 公用 url
const initialApi = {
getOrganization: async (organizationId) => {
let url = `${AuthorUrl}/api/Organization/sons/${organizationId}`;
return await callApi(async () => {
return await ApiClient.get(url);
})
},
getOrganizationOnly: async (userId) => {
let url = `${AuthorUrl}/api/Organization/${userId}`;
return await callApi(async () => {
return await ApiClient.get(url);
})
},
postStaff: async (condition) => {
let url = `${AuthorUrl}/api/user/list`;
return await callApi(async () => {
return await ApiClient.post(url, condition);
})
}
}
export default initialApi;
具体页面引入数据封装方法
// 当前数据请求封装实例
// 需要请求后端数据的页面
import initialApi from './services/initialApi'; // 初始请求接口
import addApi from './services/addApi'; // 新增请求接口
import deleteApi from './services/deleteApi'; // 删除请求接口
import editApi from './services/editApi'; // 修改请求接口
class App extends Component {
constructor(props) {
super(props);
this.state = {
organizationTreeData: [],
...
}
}
// 页面加载前,获取后端部门数据
componentDidMount() {
this.onRequstInitData();
}
onRequstInitData = async () => {
let userId = this.props.user.id
let initData = await initialApi.getOrganizationOnly(userId);
let initArr = [];
initArr.push(initData.extension);
let initList = initArr || [];
// console.log(initList);
this.setState({
organizationTreeData: initList,
})
}
网友评论