Build the scaffold of react project from scratch (Series 1: encapsulating a request method with cache function based on Axios)

Yujin 2021-05-03 18:20:01
build scaffold react project scratch


Preface

Since entry , I feel that life is really busy , Although it's an intern , But the work is still well arranged . Every day 9 It's normal to work after midnight , Go back to the rental house and take a bath 10 spot , After that, although I still want to learn something more, I still want to watch the video for a while and go to bed . I didn't travel during the May Day holiday , First, there are no friends who want to travel together , Second, I really want to have a good rest , Instead of going out to suffer, I still want to stay at school , Play a game that hasn't moved for a long time , Reading books or something .

Back to this article , In my internship experience , What I've been doing myself is a kind of odd job , The main time is the development of the page based on the framework built by elder martial brother , Although such work accounts for the vast majority of the project , But there is no doubt that , The early basic work is very important for the project , Do you have the engineering knowledge , It's also an important standard to distinguish front-end engineers from front-end cutouts . For the purpose of mastering and sharing knowledge , I decided to break it down into a series of steps , Gradually build your own React Project scaffolding .

encapsulation axios

take axios According to the needs of the business, it is packaged as exposed request Method , The overall code is relatively simple and clear , I won't explain too much here , There are also comments in the code , And there's one of them decodehtml Method , It is used to display the rich text error information returned by the back end .

/** decodeHtml */
export const decodeHtml = (html: string): string => {
let oDiv = document.createElement('div');
oDiv.innerHTML = html;
const textContent = oDiv.textContent;
oDiv = null;
return textContent;
};
 Copy code 

The following is a request Method code (src/utils/request.ts)

import { Message, Dialog } from '@alifd/next';
import axios, { AxiosRequestConfig } from 'axios';
import { decodeHtml } from '@/utils';
export interface IRequest extends AxiosRequestConfig {
url: string;
/** Request parameters , When method by post Please use data attribute */
params?: any;
/** When method by post When you use data attribute */
data?: any;
/**
* Whether to cache data , identical url Data is requested only once , All subsequent requests use the data from the first request
*/
cache?: boolean;
/** More evidence cacheKey Cache , When cache by true Effective when */
cacheKey?: string;
/**
* When wrong, whether Message Error message , Default on
*/
enableErrorMsg?: boolean;
// Cache lifetime 
maxAge?: number;
[key: string]: any;
}
// Cache storage objects , Consider freeing memory when the project is large , There is no need for 
const request_cache = {};
export interface IResult {
success?: boolean;
code?: string;
message?: string;
data?: any;
[key: string]: any;
}
// Set to ajax request 
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Data request
* @example
* request({
* url: '/a/b/c',
* params: {}
* })
* // res.success === true When it comes to execution then
* .then(res => {...})
* // res.success === false When it comes to execution catch
* .catch(res => {...})
*
* Please cooperate `ahooks` Of `useRequest` Use https://ahooks.js.org/hooks/async#dependent-request
*/
export default ({
cache = false,
enableErrorMsg = true,
cacheKey = '',
maxAge = Infinity, // Expiration time 
...params
}: IRequest) => {
// Local cache , Request only once 
if (cache && request_cache[`${params.url}-${cacheKey}`]) {
if (request_cache[`${params.url}-${cacheKey}`].then) {
return request_cache[`${params.url}-${cacheKey}`];
} else if (
new Date().getTime() -
request_cache[`${params.url}-${cacheKey}`].cacheTime <
maxAge
) {
return new Promise(resolve => {
resolve(request_cache[`${params.url}-${cacheKey}`].res);
});
}
} else if (request_cache[`${params.url}-${cacheKey}`]) {
delete request_cache[`${params.url}-${cacheKey}`];
}
if (params.method && params.method.toLowerCase() === 'post') {
// post The parameter passed in is data Field 
params.data = params.data || params.params || undefined;
// params.data = qs.stringify(params.data); // And back end conventions post Request to use json The way to transfer data , So turn it off 
params.params = undefined;
params.headers = params.headers || {
'Content-Type': 'application/json;charset=UTF-8', // And back end conventions post Request to use json The way to transfer data 
};
// If you need to do csrf The following solutions can be adopted , The backend needs to set... In the interface return information first cookie 
// if (!isLocal()) {
// const csrfToken = getCookie('XSRF-TOKEN');
// if (csrfToken) {
// params.headers['X-XSRF-TOKEN'] = csrfToken;
// } else {
// Message.error('cookie Acquisition failure '); // XSRF-TOKEN cookie defect 
// throw new Error('cookie Acquisition failure ');
// }
// }
} else if (
!params.method ||
(params.method && params.method.toLowerCase() === 'get')
) {
// get The parameter passed in when is params Field 
params.params = params.params || params.data || undefined;
}
const servicePromise = new Promise((resolve, reject) => {
axios(params)
.then(({ data: res, status }: IResult) => {
const { message, success, data, code } = res;
if (success && status === 200) {
// success 
// The data that needs to be cached is cached 
cache &&
(request_cache[`${params.url}-${cacheKey}`] = {
res,
cacheTime: new Date().getTime(),
});
resolve(res);
} else if (code === '9003') {
// State expired redirection , Back end code by 9003, there code Each team has its own rules 
Dialog.confirm({
content: ` Status expired , Whether to refresh the page again ? `,
onOk: () => {
window.location.reload();
},
});
} else if (data?.applyUrl) {
// Temporary processing without permission jump 
window.location.href = data.applyUrl;
reject(res);
} else {
// Failure 
// Whether to display error message when failure 
enableErrorMsg &&
Message.error(
`[${params.apiName || params.url}]: ${decodeHtml(message)}`
);
reject(res);
}
})
.catch(e => {
// The interface is not 200 || The interface is not 304
enableErrorMsg && Message.error(`[http]: ${e}`);
reject(e);
});
});
// One thing to consider here is , On the second request , The first request hasn't been completed yet 
// Then you can cache the first request operation first , In the second request, judge if it is still pending in , Then return to promise object , Otherwise, the result 
if (cache) {
request_cache[`${params.url}-${cacheKey}`] = servicePromise;
}
return servicePromise;
};
 Copy code 

Usage mode

All request methods in the application are placed in src/services/ Under the table of contents , Each module / The request method used by the page is placed in a corresponding js/ts In file .

//src/services/examplePage.ts

import request from '@/utils/request';
export const exampleApi = ({ data, ...elseConfig }) => {
return request({
url: `/api/reputation/evaluation/deepInsight/emotion`,
method: 'post',
data,
...elseConfig,
});
};
 Copy code 

Used on the page , Recommended match ahooks Of useRequest Use

import {exampleApi} from '@/services/examplePage.ts';
import { useRequest } from 'ahooks';
const { data, error, loading } = useRequest(()=>exampleApi({
data:{
yourInfo:''
},
cache:true,
maxAge:360000
});
 Copy code 
版权声明
本文为[Yujin]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503181827820m.html

  1. 浅谈 React 中的 XSS 攻击
  2. XSS attack in react
  3. 自学前端教程整理,附不容错过的前端100篇文章合集
  4. Self taught front-end tutorial collation, with a collection of 100 front-end articles that can not be missed
  5. 使用OpenTracing跟踪Go中的HTTP请求延迟
  6. Using opentracing to track HTTP request latency in go
  7. Encapsulating databinding allows you to write less than 10000 lines of code
  8. 03-HTML5标签-HTML5极速入门
  9. 03-html5 tag-html5 quick start
  10. LayUI - 极易上手拿来即用的前端 UI 框架
  11. Layui - easy to use front end UI framework
  12. Interpretation of lodash source code (1)
  13. Why is the first parameter of node family callback error?
  14. 报告:JavaScript 开发者达1380 万,C#超越 PHP,Rust 增长最快
  15. Report: Javascript developers reach 13.8 million, C surpasses PHP, and rust grows fastest
  16. 小白前端入门笔记(10),怎么设置网站内部的超链接?
  17. How to set up hyperlinks inside the website?
  18. Using node and socket to realize online chat room
  19. The core competitiveness of Vue: data bidirectional binding
  20. React configuration agent
  21. CSS layout
  22. Application scenario explanation of Vue dynamic component
  23. Redux learning notes 04 -- using multiple reducers to manage data
  24. After three months of typescript writing, what have I learned?
  25. Node family - what is a callback?
  26. React -- a simple implementation of render & create element
  27. JS learning simple usage of jquery
  28. Seamless love
  29. 小白前端入门笔记(12),设置哑链接
  30. Small white front-end entry notes (12), set dumb links
  31. Vue2. X opens composition API and TSX
  32. Interview record and thinking of social recruitment for one and a half years (Alibaba, Tencent, baidu offer)
  33. Flex learning notes
  34. The most essential closure article in the eastern hemisphere
  35. 2021-05-03 hot news
  36. Sword finger offer -- reverse order pair in array (JS Implementation)
  37. Working process of scaffold
  38. Use decorator mode to strengthen your fetch
  39. [JS] scope (Introduction)
  40. Employment information statistics network (interface document)
  41. Analysis of MVC
  42. [middle stage] please stay and join me in the backstage
  43. Understanding front end garbage collection
  44. [continuous update] front end special style implementation
  45. Flutter product analysis and package reduction scheme
  46. XPath positioning
  47. 前端开发css中的flex布局的使用
  48. The use of flex layout in front end development CSS
  49. JQuery核心函数和静态方法
  50. JQuery core functions and static methods
  51. Node family - understanding of blocking and non blocking
  52. 热点微前端Microfrontend的讨论:谷歌AdWords是真实的微前端
  53. Vue source code analysis (2) initproxy initialization proxy
  54. What's TM called react diff
  55. Summary of common front end data structure
  56. Useeffect in hooks
  57. [encapsulation 02 design pattern] Command pattern, share meta pattern, combination pattern, proxy pattern, strategy pattern
  58. Front end notes: virtual Dom and diff of vue2. X
  59. The best code scanning plug-in of flutter
  60. The simplest plug-in for rights management of flutter