首页
/ React性能优化规则

React性能优化规则

2026-04-03 09:38:30作者:农烁颖Land
  • 🔍 自动检测:避免在render中创建函数(问题表现:组件不必要重渲染)
  • 🔍 自动检测:列表渲染必须使用key属性(问题表现:DOM树频繁重建)
  • 🔍 自动检测:useEffect依赖数组完整(问题表现:副作用执行时机错误)

#### 后端服务场景(FastAPI)

基础规则文件:`rules/python-fastapi-cursorrules-prompt-file/fastapi-performance-optimization.mdc`

定制示例:
```markdown
# FastAPI性能优化规则
- 🔍 自动检测:路径操作函数添加响应模型(问题表现:数据序列化效率低)
- 🔍 自动检测:数据库查询使用索引(问题表现:查询响应时间>100ms)
- 🔍 自动检测:大型响应启用压缩(问题表现:传输数据量>1MB)

全栈开发场景

组合规则文件:

  • 前端:rules/nextjs-typescript-cursorrules-prompt-file/next-js-performance-optimization.mdc
  • 后端:rules/python-fastapi-best-practices-cursorrules-prompt-f/fastapi-performance-optimization.mdc

3. 规则冲突解决

当不同规则发生冲突时,可通过以下策略解决:

  1. 优先级声明:在规则前添加[HIGH]/[MEDIUM]/[LOW]标记

    [HIGH] 必须使用React.memo包装纯组件
    [LOW] 建议使用useMemo缓存计算结果
    
  2. 规则组合:创建.cursorrules文件导入多个规则集

    {
      "extends": [
        "./rules/react-performance.mdc",
        "./rules/typescript-style.mdc"
      ],
      "rules": {
        "react/no-inline-function": "error",
        "react/use-memo": "warn"
      }
    }
    

常见误区:过度配置规则。建议初始只启用核心规则(约20-30条),后续逐步增加,避免信息过载。

进阶实践:自定义规则与工作流优化

规则优先级机制深度解析

Awesome CursorRules 的规则优先级由以下因素决定(按权重排序):

  1. 显式声明:通过[HIGH]等标记直接指定
  2. 文件位置:项目根目录的规则覆盖全局规则
  3. 规则类型:错误类规则(error)优先于警告类规则(warn)
  4. 最近更新:新修改的规则优先于旧规则

自定义规则JSON Schema参考

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "id": { "type": "string", "pattern": "^[a-z0-9-]+$" },
    "name": { "type": "string" },
    "description": { "type": "string" },
    "severity": { "type": "string", "enum": ["error", "warn", "info"] },
    "pattern": { "type": "string" },
    "fixable": { "type": "boolean" },
    "frameworks": { "type": "array", "items": { "type": "string" } }
  },
  "required": ["id", "name", "pattern", "severity"]
}

同类工具对比分析

工具 优势 劣势 适用场景
Awesome CursorRules 专注性能优化,规则丰富,轻量级 生态相对较新 中小型项目、敏捷开发
ESLint + 插件 生态成熟,社区支持强 需手动配置性能规则 大型企业项目
SonarQube 全面的代码质量检查 重量级,配置复杂 大型团队、严格质量要求

规则工作流优化

性能规则工作流程图 图2:性能规则工作流程 - 开发效率工具自动化检测流程

优化后的工作流程建议:

  1. 提交前检查:配置pre-commit钩子自动运行规则检查

    # 在项目根目录创建 .git/hooks/pre-commit
    # 添加以下内容
    #!/bin/sh
    cursor-rules check --path ./src
    
  2. 规则定期更新:每月同步官方规则库更新

    git subtree pull --prefix rules https://gitcode.com/GitHub_Trending/aw/awesome-cursorrules main --squash
    
  3. 性能数据追踪:集成到CI/CD流程生成性能报告

    # .github/workflows/performance.yml 示例
    jobs:
      performance-check:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v3
          - run: npm install -g cursor-rules
          - run: cursor-rules report --output performance-report.md
登录后查看全文
热门项目推荐
相关项目推荐