将函数转换为 useCallback

Transform function to useCallback

我想重写一个函数:

function useQuery() {
  return new URLSearchParams(useLocation().search);
}

React useCallback 形式的首选,我最好的猜测是:

const useQuery = useCallback(
  () => {
    return new URLSearchParams(useLocation().search);
  },
  [useLocation]
);

我得到的错误:

React Hook "useLocation" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks

这是否意味着我无法将我的功能转换为 useCallback

useLocation是一个钩子,应该直接在组件中调用。然而,它的 result 可以在回调中使用。例如:

const location = useLocation();
const useQuery = useCallback(
    () => {
        return new URLSearchParams(location.search);
    },
    [location]
);

虽然由于 location 是一个对象,而您实际上只关心 search 值,但确定 useCallback 挂钩发生了什么变化的比较可能更准确简单值:

const { search } = useLocation();
const useQuery = useCallback(
    () => {
        return new URLSearchParams(search);
    },
    [search]
);