我有一个Reaction项目,并且已经使用Reaction路由V6附带的钩子useNavigate创建了一个定制钩子.自定义挂钩工作得很好,现在我需要阻止这个项目中的开发人员使用本地的useNavigate挂钩.我按如下方式配置了我的ESLint脚本.并且我已经安装了依赖项"eslint-plugin-action-hooks"The problem is, I'm getting the error "[eslint] Failed to load plugin 'no-react-hooks' declared in '.eslintrc.json': Cannot find module 'eslint-plugin-no-react-hooks'"

.eslintrc.json

{
  "extends": [
    "react-app",
    "plugin:no-react-hooks/recommended"
  ],
  "plugins": ["react", "no-react-hooks"],
  "rules": {
    "no-react-hook/use-navigate": "error"
  }
}

Eslint-plugin-no-react-hooks.js

module.exports = {
  rules: {
    'use-navigate': {
      meta: {
        type: 'problem',
        docs: {
          description: 'Prevent usage of the useNavigate hook',
          category: 'Best Practices',
          recommended: true,
        },
      },
      create(context) {
        return {
          ImportDeclaration(node) {
            if (
              node.source.value === 'react-router-dom' &&
              node.specifiers.some(
                (specifier) => specifier.imported.name === 'useNavigate',
              )
            ) {
              context.report({
                node: node,
                message:
                  'Do not use the useNavigate hook. Instead, use "useCustomNavigate"',
              });
            }
          },
        };
      },
    },
  },
};

我怎么才能解决这个问题?

推荐答案

我使用了一种不同的方法并解决了问题.我没有阻止开发人员使用useNavigate挂钩,而是在项目中的任何位置通过react-router-dom模块将规则设置为prevent a developer from importing that method,如下所示.(我还添加了一个使用overrides属性的异常,以显式文件使用useNavigate挂钩)

Eslintrc.json

{
  "overrides": [
    {
      "files": ["src/helper.tsx"],
      "rules": {
        "no-restricted-imports": [
          "error",
          {
            "paths": [
              {
                "name": "react-router-dom",
                "importNames": [],
                "message": "Importing useNavigate from react-router-dom is only allowed in this file."
              }
            ]
          }
        ]
      }
    }
  ],
  "rules": {
    "no-restricted-imports": [
      "error",
      {
        "paths": [
          {
            "name": "react-router-dom",
            "importNames": ["useNavigate"],
            "message": "Importing useNavigate from react-router-dom is not allowed. Instead, Import useCustomNavigate from helper.tsx"
          }
        ]
      }
    ]
  }
}

Reactjs相关问答推荐

如何将google地址lat收件箱设置为输入值?

如何防止使用useCallback和memo重新渲染

react 挂钩-使用有效澄清

如何解决Reaction中遗留的上下文API错误?

如何使用react-router-dom保护嵌套在受保护路由中的嵌套路由?

useEffect 和 ReactStrictMode

设置自定义形状的纹理

我发送的 prop 的值不会改变.如果成功登录,导航栏中的 prop 必须为 true.我从后端得到 200 ok

React Context API 在 Next.js 中更改路由时获取默认数据

我可以同时使用 Gatsby 和 NEXT.JS 吗?

React-router-dom的链接不改变路由(ReactRouter6)

Spring Boot + React + MySQL应用的架构层面有哪些?

Recharts 笛卡尔网格 - 垂直线和水平线的不同样式

改变输入的默认值时出现问题:number react-hook-form

在准备回调中使用状态属性(Redux 工具包)

在表格中显示具有自定义声明的用户状态

如何使用 babel 将 SVG 转换为 React 组件?

在状态中存储多个选定的选项

useEffect 仅在跟随链接后有效,不适用于直接链接

Context Api React 的问题