3

我在使用 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 方法中使用历史对象:

  1. 没有编译器警告(React Hook useCallback 缺少依赖项:'history'。包括它或删除依赖项 array.eslint(react-hooks/exhaustive-deps )
  2. 没有为警告添加忽略语句(// eslint-disable-line react-hooks/exhaustive-deps
  3. 不使用 window.history ,因为使用 useLocation() 钩子不能很好地工作。历史更改事件不会由 window.history 触发。因此,不能按照本文中的示例使用 useEffect 和 useLocation 挂钩:https ://reacttraining.com/blog/react-router-v5-1/?fbclid=IwAR1WHJKKeF0rO_-jW31mRCatWq5o143OvgyURn6R3uGlHNQ_dqs3QQ4ddLs
4

2 回答 2

0

对于那些想知道如何解决问题的人来说,这就是我解决问题的方法:

const navigateTo = React.useRef(history.push).current;
const handleLogUserOut = React.useCallback(() => {
    // Handle app logic...
    navigateTo('/login');
}, [ navigateTo ]);

React.useEffect(() => {
    handleLogUserOut();
}, [ handleLogUserOut ]);

我基本上将history.push方法放在 a 中React.useRef并直接调用它,这样我就不必依赖整个history对象,从而导致无限循环

于 2021-06-19T00:08:22.743 回答
0

在依赖项列表中包含历史记录是否有任何问题?这对我来说很好,我没有注意到任何额外的渲染。

不要忘记简单地改变历史状态(例如导航)只是改变现有的历史对象,而不是创建一个不同的对象,所以 useCallback 不会检测到变化

于 2020-07-07T15:55:19.400 回答