首页 > 解决方案 > 如何在 reactJS 中正确创建可重用的 useLocation 函数

问题描述

我的许多组件中都有此代码

    useLocation().pathname === `/${l.toLowerCase()}`;

现在我想创建一个函数并将这段代码放在那里,以便我只能在所有必需的组件中使用该函数。

我使用以下代码创建了 isPathMatching.jsx。

    import { useLocation } from "react-router-dom";

    const isPathMatching = (language) => {
      return useLocation().pathname === `/${language.toLowerCase()}`;
    };

    export default { isPathMatching };

我认为它应该可以工作,但是当我尝试导入其他组件时,它给了我以下错误:尝试导入错误:'isPathMatching' 不是从'../../utils/isPathMatching' 导出的。我检查了,我的导入路径是正确的。

我该如何解决这个问题?

标签: reactjsreact-router-dom

解决方案


我以这种方式更改了 isPathMatching.jsx 文件,它开始工作:

    export const isPathMatching = (useLocation, language) => {
      return useLocation.pathname === `/${language.toLowerCase()}`;
    };

推荐阅读