在 React JS 的回调中使用自定义钩子

Use custom hook inside a callback in React JS

我有这个自定义挂钩:

const useSomething = () => {
    const displayAlert = (text) => {
        alert(text);
    };
    return {displayAlert};
};

现在我想在我的代码中的某处使用它,如下所示:

const SampleComponent = () => {
    const {displayAlert} = useSomething();

    const navigateHandler = (event, page) => {
        // some api
        // ...
        displayAlert('Some alert');
    };

    const navigateHandlerCallback = useCallback(() => {
        navigateHandler(null, 1);
    }, []);

    useEffect(navigateHandlerCallback, []);

    return (
        <button onClick={e => { navigateHandler(e, 5); }}>
            Navigate to 5th page
        </button>
    )
};

现在的问题是 eslint 警告说:

React Hook useCallback has a missing dependency: 'navigateHandler'. Either include it or remove the dependency array

当我将 navigateHandler 作为依赖项包含在 useCallback 依赖项数组中时,eslint 说:

e 'navigateHandler' function makes the dependencies of useCallback Hook (at line XXX) change on every render. To fix this, wrap the 'navigateHandler' definition into its own useCallback() Hook

我该怎么办?

使用 useCallback 更新您的自定义挂钩:

const useSomething = () => {
    const displayAlert = useCallback((text) => {
        alert(text);
    };, [])
    return {displayAlert};
};

然后在你的组件中:

const SampleComponent = () => {
    const {displayAlert} = useSomething();

    const navigateHandler = useCallback((event, page) => {
        // some api
        // ...
        displayAlert('Some alert');
    }, [displayAlert]);

    const navigateHandlerCallback = useCallback(() => {
        navigateHandler(null, 1);
    }, [navigateHandler]);

    useEffect(navigateHandlerCallback, []);

    return (
        <button onClick={e => { navigateHandler(e, 5); }}>
            Navigate to 5th page
        </button>
    )
};

通过使用 useCallback 这肯定会提高渲染期间的性能。