我是靠谱客的博主 狂野大象,这篇文章主要介绍react中使用Woker线程发送异步ajax请求,现在分享给大家,希望可以做个参考。

简单封装使用

1 创建woker

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const workercode = () => { this.onmessage = function (e) { let that = this; let params = JSON.parse(e.data); if (params.type === "xhr") { let xhr = new XMLHttpRequest(); xhr.open(params.method, params.url); xhr.send(); xhr.onreadystatechange = function () { if (this.readyState === 4) { that.postMessage(this.responseText); } }; } }; }; // 把脚本代码转为string let code = workercode.toString(); code = code.substring(code.indexOf("{") + 1, code.lastIndexOf("}")); const blob = new Blob([code], { type: "application/javascript" }); const worker_script = URL.createObjectURL(blob); module.exports = worker_script;

2 runwoker

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
import worker_script from "util/woker"; function runWoker(params) { return new Promise(function (resolve, reject) { let woker = new Worker(worker_script); woker.postMessage(JSON.stringify(params)); woker.addEventListener("message", (e) => { resolve(JSON.parse(e.data)); }); }); } export default runWoker;

3 使用

复制代码
1
2
3
4
5
6
7
8
runWoker({ type: "xhr", method: "GET", url: "http://127.0.0.1:8000/home/news/?area=AREA%257C88cff55c-aaa4-e2e0", }).then((res) => { setNewsHouse(res.body); });

最后

以上就是狂野大象最近收集整理的关于react中使用Woker线程发送异步ajax请求的全部内容,更多相关react中使用Woker线程发送异步ajax请求内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(100)

评论列表共有 0 条评论

立即
投稿
返回
顶部