首页 > 解决方案 > react-hooks/exhaustive-deps 用于传递到/从自定义钩子的参考

问题描述

const useCustomHook = (refs) => {
    const { someRef } = refs;
    useEffect(() => {
        console.log(someRef.current);
    }, []); // <= react-hooks/exhaustive-deps for someRef
};

const useAnotherHook = () => {
    const anotherRef = useRef(null);
    return { anotherRef };
};

const Component = () => {
    const someRef = useRef(null);

    useCustomHook({ someRef });

    const { anotherRef } = useAnotherHook();

    useEffect(() => {
        console.log(anotherRef.current);
    }, []); // <= react-hooks/exhaustive-deps for anotherRef

    return (<div>Loading</div>);
};

当我将 ref 传递给useCustomHook钩子内部时,ref 被视为 prop,因此警告是从 eslint 报告的。与从 导出的 ref 相同useAnotherHook

如何配置 eslint 或更改代码?

标签: react-hooks

解决方案


更改useEffectuseCustomHook

const useCustomHook = (refs) => {
  const { someRef } = refs;
  React.useEffect(() => {
    console.log(someRef.current);
  }, [someRef]);
};

并更改useEffectComponent

React.useEffect(() => {
    console.log(anotherRef.current);
  }, [anotherRef]);

推荐阅读