我有这个自定义钩子:
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>
)
};
现在,问题是警告:
反应挂钩useCallback缺少依赖项:'navigateHandler'。包括它或删除依赖项数组
并且当我将 navigateHandler
作为依赖项包含到useCallback
依赖项数组中时,eslint说:
e'navigateHandler'函数使useCallback Hook(在第XXX行)的依赖项在每个渲染器上都改变。要解决此问题,请将“ navigateHandler”定义包装到其自己的useCallback()挂钩中
navigateHandler
功能。答案 0 :(得分:2)
使用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
,可以确保在渲染过程中提高性能。