如何取消ajax请求的回调
var xhr = new XMLHttpRequest(),
method = "GET",
url = "/";
xhr.onreadystatechange = () => {
if(xhr.readyState===4&&xhr.status===200){
console.log('ok')
}
}
xhr.open(method, url, true);
xhr.send();
xhr.abort();
const axios = require('axios')
// 1、获取CancelToken
var CancelToken = axios.CancelToken;
// 2、生成source
var source = CancelToken.source();
console.log(source.token)
axios.get('/user/12345', {//get请求在第二个参数
// 3、注入source.token
cancelToken: source.token
}).catch(function (thrown) {
console.log(thrown)
});
axios.post('/user/12345', {//post请求在第三个参数
name: 'new name'
}, {
cancelToken: source.token
}).catch(e=>{
console.log(e)
});
// 4、调用source.cancel("原因"),终止注入了source.token的请求
source.cancel('不想请求了');
下面来看个案例,案例页面结构如下:
class Three extends Component {
constructor(props) {
super(props)
this.state = {
arr: ''
}
}
click = () => {
axios.get("https://cnodejs.org/api/v1/topics").then(data => {
this.setState({
arr: data.data,
})
}).catch(e => {
console.log(e)
})
}
render() {
let {arr} = this.state;
return <div>
<p>{arr.length} </p>
<button onClick={this.click}>Click</button>
<Link to={'/admin/list/clock'}>首页</Link>
</div>
}
}
点击click按钮,但是在请求未返回时,我们通过导航切换到其他路由,此时浏览器就会出现警报,如图:
class Two extends Component{
constructor(props){
super(props)
// 1、调用axios.CancelToken.source()方法生成source实例;
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
this.state = {
source,
arr:''
}
}
click=()=> {
let { token } = this.state.source
// 2、将source.token以cancelToken参数形式传入axios的请求中;
axios.get("https://cnodejs.org/api/v1/topics", {
cancelToken: token
}).then(data => {
this.setState({
arr:data,
loading:'加载完成'
})
console.log(data);
}).catch(e => {
console.log(e)
})
}
componentWillUnmount(){
// 3、在组件即将卸载时取消当前组件的所有异步任务
const { cancel } = this.state.source;
cancel("销毁了")
}
render(){
let {a} = this.state
return <div>
<p>{} has clicked <strong>{a}</strong> Times </p>
<button onClick={this.click}>Click</button>
<Link to={'/admin/list/clock'}>首页</Link>
</div>
}
}
const Index = function (){
let [arr,setArr] = useState('');
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
let Click = ()=>{
axios.get("https://cnodejs.org/api/v1/topics", {
cancelToken: source.token
}).then(data => {
setArr(data.data.data);
console.log("2222");
}).catch(e => {
console.log(e)
})
}
useEffect(()=>{
return ()=>{
console.log("quxiaole")
source.cancel()
}
},[])
return <div>
<p>{arr.length} </p>
<button onClick={Click}>Click</button>
<Link to={'/admin/list/clock'}>首页</Link>
</div>
}