我找不到任何关于如何定义AbortController
类型的参考。我正在React组件中使用它,比如:
const abortController = useRef();
const doRequest = () => {
abortController.current = new AbortController();
window
.fetch(url, {
method: 'GET',
signal: abortController.current.signal,
})
.then(res => res.json());
};
const cancelRequest = () => {
abortController.current.abort();
};
type MutableRefObject<T> = {
current: T | null; // generic type
};
const abortController: MutableRefObject<AbortController> = useRef(null);
const doRequest = () => {
abortController.current = new AbortController();
window
.fetch(url, {
method: 'GET',
signal: abortController.current.signal,
})
.then(res => res.json());
};
const cancelRequest = () => {
abortController.current?.abort(); // ? for Optional chaining
};
基本上CCD_ 2的类型是CCD_。我创建了类型MutableRefObject
用于useRef
挂钩。React提供的RefObject
引发另一个错误,因为current
属性在RefObject
上是只读的。
const abortController = useRef<AbortController>();
应该工作