简体   繁体   English

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

[英]Use custom hook inside a callback in React JS

I have this custom hook:我有这个自定义钩子:

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

Now I want to use it somewhere in my code like following:现在我想在我的代码中的某个地方使用它,如下所示:

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>
    )
};

Now the problem is eslint warning that says:现在的问题是 eslint 警告说:

React Hook useCallback has a missing dependency: 'navigateHandler'. React Hook useCallback 缺少依赖项:'navigateHandler'。 Either include it or remove the dependency array包括它或删除依赖项数组

And when I include navigateHandler as a dependency into useCallback dependency array, eslint says:当我将navigateHandler作为依赖项包含在useCallback依赖项数组中时,eslint 说:

e 'navigateHandler' function makes the dependencies of useCallback Hook (at line XXX) change on every render. 'navigateHandler' 函数使 useCallback Hook(在第 XXX 行)的依赖项在每次渲染时发生变化。 To fix this, wrap the 'navigateHandler' definition into its own useCallback() Hook要解决此问题,请将 'navigateHandler' 定义包装到它自己的 useCallback() 钩子中

  • I cant change navigateHandler function.我无法更改navigateHandler函数。
  • I'm not sure if another callback can solve my problem with best performance or not.我不确定另一个回调是否可以以最佳性能解决我的问题。

👉 What should I do about this? 👉我该怎么办?

Update your custom hooks with useCallback :使用useCallback更新您的自定义钩子:

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

Then within your component:然后在您的组件中:

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>
    )
};

By using useCallback this will surely improve performance during renders.通过使用useCallback这肯定会提高渲染期间的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM