【发布时间】:2020-12-02 09:27:10
【问题描述】:
使用以下自定义 React Hook 与 IntersectionObserver 进行交互:
import { useCallback, useRef, useState } from 'react';
type IntersectionObserverResult = [(node: Element | null) => void, IntersectionObserverEntry?];
function useIntersectionObserver(options: IntersectionObserverInit): IntersectionObserverResult {
const intersectionObserver = useRef<IntersectionObserver>();
const [entry, setEntry] = useState<IntersectionObserverEntry>();
const ref = useCallback(
(node) => {
if (intersectionObserver.current) {
console.log('[useInterSectionObserver] disconnect(????)');
intersectionObserver.current.disconnect();
}
if (node) {
intersectionObserver.current = new IntersectionObserver((entries) => {
console.log('[useInterSectionObserver] callback(????)');
console.log(entries[0]);
setEntry(entries[0]);
}, options);
console.log('[useInterSectionObserver] observe(????)');
intersectionObserver.current.observe(node);
}
},
[options.root, options.rootMargin, options.threshold]
);
return [ref, entry];
}
export { useIntersectionObserver };
ESLint 抱怨:
React Hook useCallback 缺少一个依赖项:'options'。要么包含它,要么移除依赖数组。
如果我用 [options] 替换依赖项数组,ESLint 不再抱怨,但现在有一个更大的问题,渲染无限循环。
在不出现eslint(react-hooks/exhaustive-deps) 错误的情况下,实现这个自定义 React Hook 的正确方法是什么?
【问题讨论】:
标签: reactjs react-hooks eslint