我在使用Reacts useCallback挂钩时有此警告。
React Hook useCallback缺少依赖项:“历史记录”。包含它或删除依赖项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