react封装函数_react中请求接口的封装

1. 新建一个dva项目。使用antd 或者antd-mobile组件库。

$ npm install dva-cli -g

$ dva -v

$ dva new dva-quickstart

$ npm start

$ npm install antd babel-plugin-import --save

或者是

$ npm install antd-mobile babel-plugin-import --save

导入方式css

{

"entry": "src/index.js",

"env": {

"development": {

"extraBabelPlugins": [

"dva-hmr",

"transform-runtime",

["import", { "libraryName": "antd-mobile", "style": "css" }]

]

},

"production": {

"extraBabelPlugins": [

"transform-runtime",

["import", { "libraryName": "antd-mobile", "style": "css" }]

]

}

}

}

2. 在该项目的src中utils 创建名为request文件夹。

$ cd dva-quickstart

$ cd src

$ cd utils

新建文件夹名为request,然后在request文件夹下面创建名为helpers的文件夹以及index.js 和 README.md , request.js 如图所示:

在helpers 下建三个js文件 combineURL.js , isAbsoluteURL.js , serialize.js

image.png

combineURL.js中 :

// Creates a new URL by combining the specified URLs

const combineURL = (baseUrl, path) => {

return `${baseUrl.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`;

};

export default combineURL;

isAbsoluteURL.js中 :

// A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL).

// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed

// by any combination of letters, digits, plus, period, or hyphen.

// https://www.ietf.org/rfc/rfc3986.txt

const isAbsoluteURL = (url) => /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);

export default isAbsoluteURL;

serialize.js中 :

import { isPresent } from 'lib/lang';

const encode = (value) => {

return encodeURIComponent(value)

.replace(/%40/gi, '@')

.replace(/%3A/gi, ':')

.replace(/%24/g, '$')

.replace(/%2C/gi, ',')

.replace(/%20/g, '+')

.replace(/%5B/gi, '[')

.replace(/%5D/gi, ']');

};

// Encode a set of form elements as a string for submission.

const serialize = (params) => {

const ret = [];

Object.keys(params).forEach(key => {

const value = params[key];

if (isPresent(value)) {

ret.push(`${encode(key)}=${encode(value)}`);

}

});

return ret.join('&');

};

export default serialize;

3. 在utils下创建一个与request同级的lang.js

lang.js 如下:

export const is

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值