AbortController 终止请求

AbortController

//AbortController()构造函数创建一个控制器
const controller = new AbortController();

//AbortController.signal属性获取其关联 AbortSignal对象的引用。
let signal = controller.signal;

const downloadBtn = document.querySelector('.download');
const abortBtn = document.querySelector('.abort');

//发起请求
downloadBtn.addEventListener('click', fetchVideo);

//abort()方法在完成AbortControllerDOM请求(例如Fetch请求)之前将其中止。
//终止请求
abortBtn.addEventListener('click', function() {
  controller.abort();
  console.log('Download aborted');
});

function fetchVideo() {
  //...
  fetch(url, {signal}).then(function(response) {
    //...
  }).catch(function(e) {
    reports.textContent = 'Download error: ' + e.message;
  })
}

封装成hooks


import { useState, useEffect } from 'react'

export default useFetch = (param,deps) => {
	 const abortController = new AbortController()
	 const [ loading, setLoading ] = useState(false)
	 const [ data, setData ] = useState()

	useEffect(()=>{
		setLoading(true)
		fetch(param,{signal:abortController.signal})
		.then(res => setData(res))
		.finally(() => setLoading(false))
	},deps)

	useEffect(()=>() => abortController.abort())

	return { loading, data }
}

你可能感兴趣的:(javascript,react)