AbortSignal 接口表示一个信号对象( signal object ),它允许您通过
AbortController
对象与DOM请求(如Fetch)进行通信并在需要时将其中止。
const controller = new AbortController();
const { signal } = controller;
// 发送请求
fetch(url, {signal}).then(function(response) {
// do something...
}).catch(function(e) {
reports.textContent = 'Download error: ' + e.message;
})
// 中止请求 调用
controller.abort();
[React] 在antd.design.pro 中
#第一步,我们先搞一个请求
模拟一下接口很慢,随便返回点儿什么东西
// mock/test.js
function getList (req, res) {
// 模拟延时 10s
setTimeout(() => {
res.send('Ok');
}, 10000);
}
export default {
'GET /api/getlist': getList,
}
#第二步
servies里面建一个文件, 请求写好
// servies/test.js
import request from '@/utils/request';
export async function getlist({option}) {
return request(`/api/getlist`, option)
}
#第三步了哈
models 里面简单的写一下
// models/test.js
import { getlist } from '@/services/test';
export default {
namespace: 'test',
state: {
list: [],
},
effects: {
*getList({ payload, callback }, { call }) {
const response = yield call(getlist, payload);
if (callback) callback(response)
},
},
reducers: {},
}
#最后页面的代码就是下面了哈
// index.js
import React from 'react';
import { Button } from 'antd';
class Test extends React.PureComponent {
state = {
signal: null,
}
componentDidMount() {
if ("AbortController" in window) {
window.controller = new AbortController();
this.setState({
signal: window.controller.signal,
})
}
}
startRequest = () => {
const { dispatch } = this.props;
const { signal } = this.state;
dispatch({
type: 'test/getList',
payload: {
option: {
credentials: 'include',
signal,
},
},
callback: res => {
console.log(res)
},
});
}
stopRequest = () => {
if ("AbortController" in window) {
window.controller.abort();
}
}
render() {
return (
<div>
<Button onClick={this.startRequest}>发送请求</Button>
<Button onClick={this.stopRequest}>中止请求</Button>
</div>
)
}
}
export default Test;
网友评论