我在使用 Reacts useCallback 钩子时收到了这个警告。
React Hook useCallback 缺少一个依赖项:'history'。要么包含它,要么移除依赖 array.eslint(react-hooks/exhaustive-deps
import { useHistory } from "react-router-dom";
const MyFunctionalComponent = () => {
const history = useHistory();
....
const someFunction = useCallback(((param) => {
history.push({
search: `?myParam=${param}`
});
....
}), [history]); <-- Putting history object here removes the warning...
return (
<Fragment>
<Something onClick={() => someFunction(myParam)}
</Fragment>
);
}
将历史对象放在 useCallback 依赖参数中会删除警告,但将其作为此方法的依赖项是没有意义的。这个方法不依赖于历史的状态,它只是调用它的方法来更新历史。此外,我怀疑每次历史记录更改时我的父组件都会重新渲染,这违背了使用 useCallback 的目的。
我的问题是如何在我的 useCallback 方法中使用历史对象:
- 没有编译器警告(React Hook useCallback 缺少依赖项:'history'。包括它或删除依赖项 array.eslint(react-hooks/exhaustive-deps )
- 没有为警告添加忽略语句(// eslint-disable-line react-hooks/exhaustive-deps)
- 不使用 window.history ,因为使用 useLocation() 钩子不能很好地工作。历史更改事件不会由 window.history 触发。因此,不能按照本文中的示例使用 useEffect 和 useLocation 挂钩:https ://reacttraining.com/blog/react-router-v5-1/?fbclid=IwAR1WHJKKeF0rO_-jW31mRCatWq5o143OvgyURn6R3uGlHNQ_dqs3QQ4ddLs