sx-ajax
基于axios封装的ajax请求库
特性
- 全局配置 & 局部配置 & 单独请求配置
- 统一错误处理
- 成功,失败提示
- 提供restfull方法 get put post del patch
- 可打断
- promise 扩展两个方法: done finally,finally一般用于清除loading状态
基础ajax类
实例化 & 配置
import SXAjax from 'path/to/sx-ajax';
const sxAjax = new SXAjax({ // 这里传入的是自定义配置
onShowErrorTip: (response, successTip) => true, // 如何全局处理错误
onShowSuccessTip: (err, errorTip) => true, // 如何全局处理成功
isMock: (url, data, method, options) => true, // 如何判断请求是否是mock
});
// axios默认配置通过如下方式进行配置,更多配置,请查阅axios官网:
sxAjax.defaults.timeout = 20000;
sxAjax.mockDefaults.timeout = 20000;
发起请求
// 引入实例化之后的sxAjax实例
import sxAjax from 'path/to/sxAjax';
// 发起get请求
this.setState({loading: true}); // 开始显示loading
sxAjax.get('/users', {pageNum: 1, pageSize: 10})
.then((data, res) => console.log(data, res))
.catch(err => console.log(err))
.finally(() => { // 如果要使用finally方法,需要对promise对象进行扩展
this.setState({loading: false}); // 结束loading
});
打断请求
有些时候需要打断未完成的ajax请求
import sxAjax from 'path/to/sxAjax';
const getAjax = sxAjax.get('/path', options);
getAjax.then(...).finally(...);
getAjax.cancel();
注意:get,post等第一层返回的promise对象拥有cancel方法,以后then返回的promise对象没有cancel方法
与mockjs结合使用
mockjs 使用单独的实例,可以与真实ajax请求实例区分开, 用于正常请求和mock同时使用时,好区分; 创建实例,通过isMock(url, data, method, options)函数,区分哪些请求需要mock, 比如:url以约定'/mock'开头的请求,使用mock等方式。
export const mockInstance = ajax.mockInstance = sxAjax.mockInstance;
import MockAdapter from 'axios-mock-adapter';
import mockInstance from 'path/to/mockInstance';
const mock = new MockAdapter(mockInstance);
mock.onGet('/success').reply(200, {
msg: 'success',
});
ajax React 高阶组件
将$ajax属性注入到目标组件props中,目标组件可以通过this.props.ajax.get(...)方式进行使用;
每次发送请求时,保存了请求的句柄,在componentWillUnmount方法中,进行统一cancel,进行资源释放,防止组件卸载之后,ajax回调还能执行引起的bug。
const ajax = createAjaxHoc(sxAjax)
// 装饰器方式:
@ajax()
class SomeComponent extends Component {...}
// 传递参数,修改注入的props属性
@ajax({propName = 'ajax001'}) // 组件内调用:this.props.ajax001
class SomeComponent extends Component {...}
// 直接使用
const WrappedComponet = ajax()(SomeComponent);