@umacloud/knowledge 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/00-governance/governance-capabilities.md +557 -0
- package/00-governance/knowledge-map.md +39 -0
- package/00-governance/maintenance-policy.md +76 -0
- package/00-governance/review-checklist.md +81 -0
- package/README.md +13 -0
- package/ai/01-standards/agent-development-complete.md +691 -0
- package/ai/01-standards/llm-application-complete.md +488 -0
- package/ai/01-standards/mlops-complete.md +798 -0
- package/ai/01-standards/prompt-engineering-complete.md +646 -0
- package/ai/01-standards/rag-architecture-complete.md +649 -0
- package/ai/02-playbooks/llm-evaluation-playbook.md +847 -0
- package/ai/03-checklists/ai-project-checklist.md +215 -0
- package/ai/04-antipatterns/ai-antipatterns.md +661 -0
- package/ai/05-cases/case-rag-production.md +147 -0
- package/ai/06-glossary/ai-glossary.md +162 -0
- package/ai/agent-evaluation-benchmark.md +53 -0
- package/ai/ai-agent-memory-context-management.md +41 -0
- package/ai/ai-cost-capacity-optimization-playbook.md +42 -0
- package/ai/ai-data-security-and-compliance-playbook.md +37 -0
- package/ai/ai-domain-index-and-checklist.md +40 -0
- package/ai/ai-governance-maturity-model.md +50 -0
- package/ai/ai-model-selection-and-routing-strategy.md +47 -0
- package/ai/ai-observability-and-oncall-runbook.md +52 -0
- package/ai/ai-rag-engineering-playbook.md +42 -0
- package/ai/ai-red-team-and-safety-evaluation.md +42 -0
- package/ai/ai-release-readiness-and-rollback-gate.md +42 -0
- package/ai/llm-agent-engineering-deep-dive.md +57 -0
- package/ai/prompt-and-tool-guardrails.md +52 -0
- package/api/01-standards/enterprise-api-standards.md +198 -0
- package/api/01-standards/rest-api-design-guide.md +63 -0
- package/api/02-playbooks/api-pagination-playbook.md +93 -0
- package/api/02-playbooks/graphql-production-playbook.md +176 -0
- package/api/03-checklists/api-review-checklist.md +55 -0
- package/api/04-antipatterns/api-antipatterns.md +112 -0
- package/architecture/01-standards/api-gateway-patterns.md +496 -0
- package/architecture/01-standards/cloud-native-patterns.md +644 -0
- package/architecture/01-standards/distributed-systems-patterns.md +591 -0
- package/architecture/01-standards/event-driven-architecture.md +595 -0
- package/architecture/01-standards/microservices-patterns-complete.md +968 -0
- package/architecture/01-standards/microservices-patterns.md +495 -0
- package/architecture/01-standards/system-design-interview.md +664 -0
- package/architecture/02-playbooks/microservices-patterns-playbook.md +137 -0
- package/architecture/02-playbooks/migration-playbook.md +780 -0
- package/architecture/02-playbooks/system-design-playbook.md +779 -0
- package/architecture/03-checklists/architecture-decision-checklist.md +297 -0
- package/architecture/04-antipatterns/architecture-antipatterns.md +417 -0
- package/architecture/05-cases/case-netflix-microservices.md +413 -0
- package/architecture/06-glossary/architecture-glossary.md +164 -0
- package/architecture/adr-template-and-examples.md +38 -0
- package/architecture/api-gateway-deep-dive.md +1291 -0
- package/architecture/configuration-management.md +1162 -0
- package/architecture/distributed-transactions.md +1220 -0
- package/architecture/microservices-complete.md +735 -0
- package/architecture/resilience-and-disaster-patterns.md +37 -0
- package/architecture/service-governance.md +1198 -0
- package/architecture/system-architecture-deep-dive.md +37 -0
- package/backend/01-standards/analytics-and-growth.md +65 -0
- package/backend/01-standards/api-and-error-conventions.md +120 -0
- package/backend/01-standards/application-layering-and-packaging.md +160 -0
- package/backend/01-standards/auth-implementation.md +104 -0
- package/backend/01-standards/backend-framework-idioms.md +74 -0
- package/backend/01-standards/background-jobs-and-async.md +66 -0
- package/backend/01-standards/caching-strategies-complete.md +390 -0
- package/backend/01-standards/config-and-observability.md +77 -0
- package/backend/01-standards/data-modeling-and-persistence.md +94 -0
- package/backend/01-standards/django-complete.md +1765 -0
- package/backend/01-standards/email-and-notifications.md +64 -0
- package/backend/01-standards/fastapi-complete.md +925 -0
- package/backend/01-standards/file-upload-and-storage.md +66 -0
- package/backend/01-standards/graphql-api-complete.md +416 -0
- package/backend/01-standards/llm-application-standard.md +78 -0
- package/backend/01-standards/message-queue-patterns.md +379 -0
- package/backend/01-standards/microservices-and-distributed.md +78 -0
- package/backend/01-standards/nestjs-complete.md +2167 -0
- package/backend/01-standards/payment-integration.md +80 -0
- package/backend/01-standards/rate-limiting-complete.md +451 -0
- package/backend/01-standards/realtime-and-websocket.md +65 -0
- package/backend/01-standards/search-and-filtering.md +64 -0
- package/backend/01-standards/spring-boot-complete.md +445 -0
- package/backend/02-playbooks/api-design-playbook.md +718 -0
- package/backend/02-playbooks/email-send-playbook.md +130 -0
- package/backend/02-playbooks/file-upload-s3-playbook.md +153 -0
- package/backend/02-playbooks/typescript-enterprise-playbook.md +133 -0
- package/backend/02-playbooks/websocket-realtime-playbook.md +154 -0
- package/backend/03-checklists/api-launch-checklist.md +189 -0
- package/backend/04-antipatterns/backend-antipatterns.md +1051 -0
- package/blockchain/01-standards/blockchain-basics.md +557 -0
- package/blockchain/01-standards/smart-contract-development.md +1315 -0
- package/cicd/01-standards/deployment-and-delivery-standard.md +96 -0
- package/cicd/01-standards/github-actions-complete.md +473 -0
- package/cicd/01-standards/release-and-store-submission.md +75 -0
- package/cicd/02-playbooks/cicd-pipeline-playbook.md +144 -0
- package/cicd/02-playbooks/release-management-playbook.md +605 -0
- package/cicd/03-checklists/pipeline-security-checklist.md +168 -0
- package/cicd/04-antipatterns/cicd-antipatterns.md +589 -0
- package/cicd/05-cases/case-deployment-automation.md +221 -0
- package/cicd/05-cases/case-gitops-transformation.md +212 -0
- package/cicd/06-glossary/cicd-glossary.md +114 -0
- package/cicd/cicd-blueprint-deep-dive.md +38 -0
- package/cicd/release-readiness-gate.md +37 -0
- package/cloud-native/01-standards/container-security.md +741 -0
- package/cloud-native/01-standards/kubernetes-complete.md +812 -0
- package/cloud-native/02-playbooks/api-gateway-playbook.md +155 -0
- package/cloud-native/02-playbooks/gitops-with-argocd.md +760 -0
- package/cloud-native/02-playbooks/k8s-troubleshooting-playbook.md +1942 -0
- package/cloud-native/02-playbooks/message-queue-playbook.md +129 -0
- package/cloud-native/02-playbooks/multicloud-governance.md +726 -0
- package/cloud-native/02-playbooks/serverless-patterns.md +788 -0
- package/cloud-native/02-playbooks/service-mesh-playbook.md +612 -0
- package/cloud-native/02-playbooks/terraform-iac-playbook.md +143 -0
- package/cloud-native/03-checklists/container-security-checklist.md +431 -0
- package/cloud-native/03-checklists/k8s-production-readiness-checklist.md +460 -0
- package/cloud-native/04-antipatterns/container-antipatterns.md +660 -0
- package/cloud-native/04-antipatterns/k8s-antipatterns.md +743 -0
- package/cloud-native/05-cases/case-k8s-migration.md +478 -0
- package/cloud-native/05-cases/case-k8s-scaling.md +642 -0
- package/cloud-native/05-cases/case-k8s-security-incident.md +397 -0
- package/cloud-native/06-glossary/cloud-native-glossary.md +337 -0
- package/cross-platform/01-standards/cross-platform-frameworks.md +83 -0
- package/cross-platform/01-standards/platform-selection-and-architecture.md +77 -0
- package/data/01-standards/elasticsearch-complete.md +2098 -0
- package/data/01-standards/postgresql-complete.md +1613 -0
- package/data/01-standards/redis-complete.md +1527 -0
- package/data/02-playbooks/database-optimization-playbook.md +403 -0
- package/data/02-playbooks/elasticsearch-production-playbook.md +132 -0
- package/data/03-checklists/database-launch-checklist.md +187 -0
- package/data/04-antipatterns/database-antipatterns.md +873 -0
- package/data/05-cases/case-database-migration.md +310 -0
- package/data/06-glossary/database-glossary.md +440 -0
- package/data/data-governance-and-modeling-deep-dive.md +39 -0
- package/data-engineering/01-standards/airflow-complete.md +523 -0
- package/data-engineering/01-standards/kafka-complete.md +1521 -0
- package/data-engineering/02-playbooks/spark-etl-playbook.md +496 -0
- package/data-engineering/03-checklists/pipeline-launch-checklist.md +194 -0
- package/data-engineering/04-antipatterns/data-pipeline-antipatterns.md +684 -0
- package/data-engineering/05-cases/case-real-time-pipeline.md +355 -0
- package/data-engineering/06-glossary/data-engineering-glossary.md +429 -0
- package/database/01-standards/database-schema-standards.md +147 -0
- package/database/02-playbooks/postgresql-optimization-quick.md +52 -0
- package/database/02-playbooks/postgresql-performance-optimization.md +58 -0
- package/database/02-playbooks/postgresql-production-playbook.md +146 -0
- package/database/02-playbooks/redis-caching-playbook.md +117 -0
- package/database/03-checklists/database-review-checklist.md +50 -0
- package/database/04-antipatterns/database-antipatterns.md +112 -0
- package/design/01-standards/ui-design-system-complete.md +423 -0
- package/design/02-playbooks/design-handoff-playbook.md +254 -0
- package/design/02-playbooks/design-review-playbook.md +388 -0
- package/design/03-checklists/design-review-checklist.md +246 -0
- package/design/04-antipatterns/design-antipatterns.md +378 -0
- package/design/05-cases/case-design-system-adoption.md +328 -0
- package/design/06-glossary/design-glossary.md +329 -0
- package/design/ui-full-lifecycle-cross-platform-playbook.md +571 -0
- package/design/ux-system-deep-dive.md +38 -0
- package/design-systems/00-craft-rules.md +71 -0
- package/design-systems/aesthetic-families.md +43 -0
- package/design-systems/anti-ai-slop.md +162 -0
- package/design-systems/bold-geometric.md +120 -0
- package/design-systems/brutalist-bold.md +103 -0
- package/design-systems/editorial-clean.md +109 -0
- package/design-systems/glass-aurora.md +108 -0
- package/design-systems/modern-minimal.md +145 -0
- package/design-systems/premium-luxury.md +106 -0
- package/design-systems/product-type-design-map.md +48 -0
- package/design-systems/soft-warm.md +123 -0
- package/design-systems/tech-utility.md +113 -0
- package/desktop/01-standards/desktop-app-standard.md +72 -0
- package/desktop/01-standards/desktop-design.md +71 -0
- package/development/00-governance/document-template.md +41 -0
- package/development/01-standards/api-versioning-strategies.md +432 -0
- package/development/01-standards/authentication-patterns-complete.md +479 -0
- package/development/01-standards/css-architecture-complete.md +550 -0
- package/development/01-standards/database-migration-strategies.md +484 -0
- package/development/01-standards/elasticsearch-complete.md +347 -0
- package/development/01-standards/git-complete.md +371 -0
- package/development/01-standards/golang-complete.md +1565 -0
- package/development/01-standards/graphql-complete.md +298 -0
- package/development/01-standards/javascript-bundlers-complete.md +469 -0
- package/development/01-standards/javascript-typescript-complete.md +528 -0
- package/development/01-standards/jest-complete.md +275 -0
- package/development/01-standards/linux-complete.md +234 -0
- package/development/01-standards/logging-observability-complete.md +526 -0
- package/development/01-standards/microservices-communication.md +502 -0
- package/development/01-standards/mongodb-complete.md +406 -0
- package/development/01-standards/oauth2-complete.md +285 -0
- package/development/01-standards/performance-optimization-complete.md +289 -0
- package/development/01-standards/playwright-complete.md +247 -0
- package/development/01-standards/postgresql-complete.md +456 -0
- package/development/01-standards/pytest-complete.md +340 -0
- package/development/01-standards/python-async-programming.md +902 -0
- package/development/01-standards/python-complete.md +956 -0
- package/development/01-standards/python-decorators-complete.md +799 -0
- package/development/01-standards/python-design-patterns.md +2854 -0
- package/development/01-standards/python-packaging-distribution.md +420 -0
- package/development/01-standards/python-testing-strategies.md +607 -0
- package/development/01-standards/python-web-frameworks-comparison.md +471 -0
- package/development/01-standards/redis-complete.md +317 -0
- package/development/01-standards/rest-api-complete.md +316 -0
- package/development/01-standards/rust-complete.md +578 -0
- package/development/01-standards/typescript-advanced-types.md +1513 -0
- package/development/01-standards/web-security-complete.md +292 -0
- package/development/02-playbooks/api-design-playbook.md +810 -0
- package/development/02-playbooks/database-migration-playbook.md +580 -0
- package/development/02-playbooks/debugging-playbook.md +692 -0
- package/development/02-playbooks/feature-delivery-playbook.md +430 -0
- package/development/02-playbooks/incident-hotfix-playbook.md +387 -0
- package/development/02-playbooks/performance-optimization-playbook.md +531 -0
- package/development/02-playbooks/performance-tuning-playbook.md +652 -0
- package/development/02-playbooks/refactor-playbook.md +403 -0
- package/development/02-playbooks/release-playbook.md +469 -0
- package/development/03-checklists/architecture-review-checklist.md +168 -0
- package/development/03-checklists/data-migration-checklist.md +157 -0
- package/development/03-checklists/oncall-handover-checklist.md +173 -0
- package/development/03-checklists/pr-checklist.md +158 -0
- package/development/03-checklists/production-readiness-checklist.md +190 -0
- package/development/03-checklists/release-readiness-checklist.md +154 -0
- package/development/03-checklists/security-review-checklist.md +182 -0
- package/development/04-antipatterns/api-antipatterns.md +657 -0
- package/development/04-antipatterns/architecture-antipatterns.md +686 -0
- package/development/04-antipatterns/backend-antipatterns.md +648 -0
- package/development/04-antipatterns/cicd-antipatterns.md +540 -0
- package/development/04-antipatterns/code-smell-antipatterns.md +571 -0
- package/development/04-antipatterns/data-antipatterns.md +658 -0
- package/development/04-antipatterns/database-antipatterns.md +578 -0
- package/development/04-antipatterns/frontend-antipatterns.md +635 -0
- package/development/04-antipatterns/reliability-antipatterns.md +700 -0
- package/development/04-antipatterns/security-antipatterns.md +747 -0
- package/development/05-cases/case-api-version-migration.md +428 -0
- package/development/05-cases/case-authorization-hardening.md +383 -0
- package/development/05-cases/case-bluegreen-rollback.md +466 -0
- package/development/05-cases/case-cache-snowball-protection.md +485 -0
- package/development/05-cases/case-ci-cd-pipeline.md +544 -0
- package/development/05-cases/case-database-scaling.md +500 -0
- package/development/05-cases/case-db-hotspot-optimization.md +487 -0
- package/development/05-cases/case-incident-mttr-reduction.md +563 -0
- package/development/05-cases/case-microservice-migration.md +375 -0
- package/development/05-cases/case-performance-optimization.md +406 -0
- package/development/05-cases/case-security-incident-response.md +345 -0
- package/development/06-glossary/full-stack-glossary.md +166 -0
- package/development/09-maturity/quarterly-audit-template.md +35 -0
- package/development/11-ui-excellence/ui-aesthetic-system.md +41 -0
- package/development/11-ui-excellence/ui-engineering-excellence.md +435 -0
- package/development/12-scenarios/development-scenarios-guide.md +565 -0
- package/development/13-implementation-assets/implementation-toolkit.md +282 -0
- package/development/13-implementation-assets/knowledge-gates-execution.md +43 -0
- package/development/14-full-lifecycle/software-lifecycle-gates.md +511 -0
- package/development/15-lifecycle-templates/project-templates-collection.md +791 -0
- package/development/api-contract-and-versioning-guide.md +36 -0
- package/development/api-governance-complete.md +43 -0
- package/development/backend-engineering-complete.md +43 -0
- package/development/code-review-quality-complete.md +43 -0
- package/development/concurrency-reliability-complete.md +43 -0
- package/development/database-engineering-complete.md +43 -0
- package/development/engineering-effectiveness-complete.md +43 -0
- package/development/engineering-standards-deep-dive.md +38 -0
- package/development/frontend-engineering-complete.md +43 -0
- package/development/performance-capacity-complete.md +43 -0
- package/development/refactor-migration-complete.md +42 -0
- package/development/refactoring-and-techdebt-playbook.md +37 -0
- package/development/security-in-development-complete.md +43 -0
- package/devops/01-standards/cicd-pipeline-complete.md +262 -0
- package/devops/01-standards/docker-complete.md +1490 -0
- package/devops/01-standards/github-actions-complete.md +337 -0
- package/devops/01-standards/kubernetes-complete.md +638 -0
- package/devops/01-standards/terraform-complete.md +2117 -0
- package/devops/02-playbooks/docker-compose-playbook.md +233 -0
- package/devops/02-playbooks/docker-k8s-production-playbook.md +186 -0
- package/devops/02-playbooks/docker-production-playbook.md +952 -0
- package/edge-iot/01-standards/edge-iot-complete.md +473 -0
- package/experts/architect/api-design.md +178 -0
- package/experts/architect/methodology.md +124 -0
- package/experts/architect/security.md +75 -0
- package/experts/backend-lead/methodology.md +216 -0
- package/experts/devops/methodology.md +160 -0
- package/experts/frontend-lead/methodology.md +178 -0
- package/experts/product-manager/industry/ecommerce.md +43 -0
- package/experts/product-manager/industry/saas.md +40 -0
- package/experts/product-manager/methodology.md +97 -0
- package/experts/qa-lead/methodology.md +123 -0
- package/experts/qa-lead/test-strategy.md +128 -0
- package/experts/uiux-designer/methodology.md +125 -0
- package/frontend/01-standards/accessibility-complete.md +532 -0
- package/frontend/01-standards/accessibility-standard.md +74 -0
- package/frontend/01-standards/admin-dashboard-and-crud.md +72 -0
- package/frontend/01-standards/design-tokens-complete.md +444 -0
- package/frontend/01-standards/forms-and-validation.md +77 -0
- package/frontend/01-standards/frontend-architecture-and-layering.md +119 -0
- package/frontend/01-standards/i18n-and-localization.md +65 -0
- package/frontend/01-standards/nextjs-complete.md +451 -0
- package/frontend/01-standards/react-complete.md +713 -0
- package/frontend/01-standards/react-hooks-complete-guide.md +1100 -0
- package/frontend/01-standards/react-hooks-complete.md +1171 -0
- package/frontend/01-standards/seo-and-web-vitals.md +77 -0
- package/frontend/01-standards/state-management-complete.md +444 -0
- package/frontend/01-standards/vue-complete.md +499 -0
- package/frontend/01-standards/vue3-complete.md +2002 -0
- package/frontend/01-standards/web-framework-best-practices.md +64 -0
- package/frontend/01-standards/web-performance-complete.md +495 -0
- package/frontend/02-playbooks/accessibility-a11y-playbook.md +161 -0
- package/frontend/02-playbooks/frontend-performance-playbook.md +707 -0
- package/frontend/02-playbooks/i18n-internationalization-playbook.md +120 -0
- package/frontend/02-playbooks/performance-optimization-playbook.md +163 -0
- package/frontend/02-playbooks/react-nextjs-production-playbook.md +167 -0
- package/frontend/02-playbooks/react-state-management-playbook.md +173 -0
- package/frontend/03-checklists/component-quality-checklist.md +166 -0
- package/frontend/03-checklists/frontend-launch-checklist.md +299 -0
- package/frontend/04-antipatterns/frontend-antipatterns.md +886 -0
- package/frontend/05-cases/case-performance-optimization.md +274 -0
- package/harmony/01-standards/harmonyos-arkts-standard.md +75 -0
- package/harmony/01-standards/harmonyos-design.md +65 -0
- package/high-quality-engineering-playbook.md +54 -0
- package/incident/01-standards/incident-response-complete.md +303 -0
- package/incident/02-playbooks/chaos-engineering-playbook.md +883 -0
- package/incident/02-playbooks/postmortem-playbook.md +398 -0
- package/incident/03-checklists/incident-readiness-checklist.md +181 -0
- package/incident/04-antipatterns/incident-antipatterns.md +490 -0
- package/incident/05-cases/case-cascade-failure.md +176 -0
- package/incident/06-glossary/incident-glossary.md +114 -0
- package/incident/postmortem-and-response-deep-dive.md +39 -0
- package/industries/ecommerce/ecommerce-complete.md +631 -0
- package/industries/education/education-complete.md +555 -0
- package/industries/fintech/fintech-complete.md +501 -0
- package/industries/gaming/gaming-complete.md +587 -0
- package/industries/healthcare/healthcare-complete.md +452 -0
- package/low-code/01-standards/low-code-complete.md +944 -0
- package/miniprogram/01-standards/ai-common-mistakes.md +61 -0
- package/miniprogram/01-standards/miniprogram-custom-navbar-capsule.md +77 -0
- package/miniprogram/01-standards/miniprogram-design.md +61 -0
- package/miniprogram/01-standards/miniprogram-standard.md +81 -0
- package/mobile/01-standards/android-material-design.md +70 -0
- package/mobile/01-standards/flutter-complete.md +384 -0
- package/mobile/01-standards/ios-design-hig.md +78 -0
- package/mobile/01-standards/mobile-app-standard.md +85 -0
- package/mobile/01-standards/react-native-complete.md +352 -0
- package/mobile/02-playbooks/mobile-cross-platform-playbook.md +175 -0
- package/mobile/02-playbooks/mobile-performance.md +473 -0
- package/mobile/03-checklists/mobile-release-checklist.md +234 -0
- package/mobile/04-antipatterns/mobile-antipatterns.md +798 -0
- package/mobile/05-cases/case-app-performance.md +500 -0
- package/mobile/05-cases/case-app-startup-optimization.md +218 -0
- package/mobile/06-glossary/mobile-glossary.md +484 -0
- package/observability/01-standards/observability-standards.md +103 -0
- package/observability/02-playbooks/prometheus-grafana-playbook.md +135 -0
- package/observability/02-playbooks/structured-logging-playbook.md +73 -0
- package/observability/03-checklists/observability-checklist.md +54 -0
- package/observability/04-antipatterns/observability-antipatterns.md +106 -0
- package/operations/01-standards/prometheus-monitoring-complete.md +1578 -0
- package/operations/02-playbooks/capacity-planning-playbook.md +620 -0
- package/operations/03-checklists/production-launch-checklist.md +365 -0
- package/operations/04-antipatterns/operations-antipatterns.md +664 -0
- package/operations/05-cases/case-sre-practices.md +581 -0
- package/operations/06-glossary/operations-glossary.md +120 -0
- package/operations/aiops-anomaly-detection.md +758 -0
- package/operations/capacity-planning.md +1061 -0
- package/operations/chaos-engineering.md +659 -0
- package/operations/incident-command-system.md +38 -0
- package/operations/observability-complete.md +442 -0
- package/operations/slo-sli-playbook.md +517 -0
- package/operations/sre-operations-deep-dive.md +39 -0
- package/package.json +8 -0
- package/performance/01-standards/performance-and-scalability.md +80 -0
- package/performance/01-standards/performance-standards.md +156 -0
- package/performance/02-playbooks/query-optimization-playbook.md +103 -0
- package/performance/03-checklists/performance-checklist.md +56 -0
- package/performance/04-antipatterns/performance-antipatterns.md +146 -0
- package/product/01-standards/product-management-complete.md +285 -0
- package/product/02-playbooks/feature-launch-playbook.md +207 -0
- package/product/02-playbooks/user-research-playbook.md +532 -0
- package/product/03-checklists/feature-launch-checklist.md +275 -0
- package/product/04-antipatterns/product-antipatterns.md +355 -0
- package/product/05-cases/case-mvp-to-scale.md +384 -0
- package/product/06-glossary/product-glossary.md +462 -0
- package/product/feature-prioritization-framework.md +40 -0
- package/product/kpi-and-metric-tree.md +37 -0
- package/product/product-discovery-and-prd-deep-dive.md +41 -0
- package/quantum/01-standards/quantum-complete.md +1186 -0
- package/security/01-standards/api-security-complete.md +511 -0
- package/security/01-standards/container-runtime-security.md +574 -0
- package/security/01-standards/data-protection-gdpr.md +543 -0
- package/security/01-standards/owasp-top10-complete.md +1890 -0
- package/security/01-standards/secure-coding-baseline.md +90 -0
- package/security/01-standards/supply-chain-security.md +441 -0
- package/security/01-standards/web-security-checklist.md +108 -0
- package/security/01-standards/zero-trust-architecture.md +521 -0
- package/security/02-playbooks/auth-sso-playbook.md +166 -0
- package/security/02-playbooks/incident-response-security-playbook.md +588 -0
- package/security/02-playbooks/owasp-api-security-playbook.md +129 -0
- package/security/02-playbooks/payment-integration-playbook.md +119 -0
- package/security/02-playbooks/penetration-testing-playbook.md +517 -0
- package/security/03-checklists/security-audit-checklist.md +356 -0
- package/security/04-antipatterns/security-coding-antipatterns.md +580 -0
- package/security/05-cases/case-log4shell-incident.md +537 -0
- package/security/05-cases/case-major-breaches.md +468 -0
- package/security/06-glossary/security-glossary.md +212 -0
- package/security/compliance-automation.md +993 -0
- package/security/container-security.md +680 -0
- package/security/devsecops-complete.md +426 -0
- package/security/sast-dast-sca.md +775 -0
- package/security/secrets-management.md +594 -0
- package/security/security-architecture-deep-dive.md +37 -0
- package/security/threat-modeling-stride-playbook.md +40 -0
- package/seed-templates/auth-system.md +59 -0
- package/seed-templates/blog-content.md +94 -0
- package/seed-templates/dashboard.md +89 -0
- package/seed-templates/docs-site.md +73 -0
- package/seed-templates/e-commerce.md +50 -0
- package/seed-templates/saas-landing.md +92 -0
- package/seed-templates/settings-page.md +51 -0
- package/testing/01-standards/test-strategy-and-layering.md +83 -0
- package/testing/01-standards/testing-strategy-complete.md +422 -0
- package/testing/01-standards/unit-testing-best-practices.md +118 -0
- package/testing/02-playbooks/e2e-testing-playbook.md +988 -0
- package/testing/02-playbooks/testing-strategy-playbook.md +126 -0
- package/testing/03-checklists/test-strategy-checklist.md +208 -0
- package/testing/04-antipatterns/testing-antipatterns.md +718 -0
- package/testing/05-cases/case-testing-transformation.md +300 -0
- package/testing/06-glossary/testing-glossary.md +110 -0
- package/testing/risk-based-test-matrix.md +36 -0
- package/testing/testing-strategy-deep-dive.md +37 -0
|
@@ -0,0 +1,1100 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: react-hooks-complete-guide
|
|
3
|
+
title: React Hooks 完全指南 - 从入门到精通
|
|
4
|
+
domain: frontend
|
|
5
|
+
category: 01-standards
|
|
6
|
+
difficulty: intermediate
|
|
7
|
+
tags: [react, hooks, frontend, javascript, state-management]
|
|
8
|
+
quality_score: 93
|
|
9
|
+
maintainer: frontend-team@umadev.com
|
|
10
|
+
last_updated: 2026-03-29
|
|
11
|
+
version: 2.5
|
|
12
|
+
related_knowledge:
|
|
13
|
+
- react-complete
|
|
14
|
+
- javascript-async-programming
|
|
15
|
+
- state-management-patterns
|
|
16
|
+
prerequisites:
|
|
17
|
+
- javascript-complete
|
|
18
|
+
- react-basics
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
# React Hooks 完全指南 - 从入门到精通
|
|
22
|
+
|
|
23
|
+
## 概述
|
|
24
|
+
|
|
25
|
+
React Hooks 是 React 16.8 引入的革命性特性,它允许你在函数组件中使用状态和其他 React 特性,而无需编写类组件。Hooks 的出现彻底改变了 React 应用的编写方式,使代码更简洁、更易复用、更易测试。
|
|
26
|
+
|
|
27
|
+
本指南将全面讲解 React Hooks 的核心概念、常用 Hooks 的深度用法、自定义 Hooks 的最佳实践,以及 Hooks 在实际项目中的高级应用模式。
|
|
28
|
+
|
|
29
|
+
## 核心概念
|
|
30
|
+
|
|
31
|
+
### 1. 为什么需要 Hooks?
|
|
32
|
+
|
|
33
|
+
在 Hooks 出现之前,React 组件面临三大问题:
|
|
34
|
+
|
|
35
|
+
1. **状态逻辑难以复用**: 类组件的状态逻辑分散在生命周期方法中,难以提取和复用
|
|
36
|
+
2. **复杂组件难以理解**: 相关逻辑分散在不同生命周期方法中,不相关逻辑混在一起
|
|
37
|
+
3. **类组件的 this 指向问题**: 需要正确绑定事件处理器,容易出错
|
|
38
|
+
|
|
39
|
+
```mermaid
|
|
40
|
+
graph TD
|
|
41
|
+
A[Class Component 问题] --> B[状态逻辑难以复用]
|
|
42
|
+
A --> C[复杂组件难以理解]
|
|
43
|
+
A --> D[this 指向问题]
|
|
44
|
+
|
|
45
|
+
E[Hooks 解决方案] --> F[自定义 Hooks 复用逻辑]
|
|
46
|
+
E --> G[相关逻辑组织在一起]
|
|
47
|
+
E --> H[无需 this,函数组件]
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### 2. Hooks 的两条黄金法则
|
|
51
|
+
|
|
52
|
+
#### 法则 1: 只在顶层调用 Hooks
|
|
53
|
+
|
|
54
|
+
```javascript
|
|
55
|
+
// ❌ 错误: 在条件语句中调用 Hook
|
|
56
|
+
if (isLoading) {
|
|
57
|
+
const [data, setData] = useState(null);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ❌ 错误: 在循环中调用 Hook
|
|
61
|
+
items.forEach(item => {
|
|
62
|
+
const [state, setState] = useState(item);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// ❌ 错误: 在嵌套函数中调用 Hook
|
|
66
|
+
function handleClick() {
|
|
67
|
+
const [count, setCount] = useState(0);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ✅ 正确: 在组件顶层调用
|
|
71
|
+
function MyComponent() {
|
|
72
|
+
const [data, setData] = useState(null);
|
|
73
|
+
const [count, setCount] = useState(0);
|
|
74
|
+
|
|
75
|
+
if (isLoading) {
|
|
76
|
+
// 使用 data
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
#### 法则 2: 只在 React 函数中调用 Hooks
|
|
82
|
+
|
|
83
|
+
```javascript
|
|
84
|
+
// ❌ 错误: 在普通 JavaScript 函数中调用
|
|
85
|
+
function formatData(data) {
|
|
86
|
+
const [formatted, setFormatted] = useState(data);
|
|
87
|
+
return formatted;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ✅ 正确: 在 React 组件中调用
|
|
91
|
+
function DataFormatter({ data }) {
|
|
92
|
+
const [formatted, setFormatted] = useState(data);
|
|
93
|
+
return <div>{formatted}</div>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ✅ 正确: 在自定义 Hook 中调用
|
|
97
|
+
function useFormattedData(initialData) {
|
|
98
|
+
const [formatted, setFormatted] = useState(initialData);
|
|
99
|
+
// ...
|
|
100
|
+
return formatted;
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### 3. Hooks 的执行顺序
|
|
105
|
+
|
|
106
|
+
React 依赖 Hooks 的调用顺序来正确保存内部状态。
|
|
107
|
+
|
|
108
|
+
```mermaid
|
|
109
|
+
sequenceDiagram
|
|
110
|
+
participant Render1 as 第一次渲染
|
|
111
|
+
participant Render2 as 第二次渲染
|
|
112
|
+
participant Hook1 as useState #1
|
|
113
|
+
participant Hook2 as useEffect #2
|
|
114
|
+
participant Hook3 as useState #3
|
|
115
|
+
|
|
116
|
+
Render1->>Hook1: 调用顺序 1
|
|
117
|
+
Render1->>Hook2: 调用顺序 2
|
|
118
|
+
Render1->>Hook3: 调用顺序 3
|
|
119
|
+
|
|
120
|
+
Note over Hook1,Hook2,Hook3: React 记住顺序
|
|
121
|
+
|
|
122
|
+
Render2->>Hook1: 调用顺序 1 (相同)
|
|
123
|
+
Render2->>Hook2: 调用顺序 2 (相同)
|
|
124
|
+
Render2->>Hook3: 调用顺序 3 (相同)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## 核心 Hooks 深度讲解
|
|
128
|
+
|
|
129
|
+
### 1. useState - 状态管理
|
|
130
|
+
|
|
131
|
+
#### 基础用法
|
|
132
|
+
|
|
133
|
+
```javascript
|
|
134
|
+
import { useState } from 'react';
|
|
135
|
+
|
|
136
|
+
function Counter() {
|
|
137
|
+
// 声明状态变量 count,初始值为 0
|
|
138
|
+
const [count, setCount] = useState(0);
|
|
139
|
+
|
|
140
|
+
return (
|
|
141
|
+
<div>
|
|
142
|
+
<p>Count: {count}</p>
|
|
143
|
+
<button onClick={() => setCount(count + 1)}>
|
|
144
|
+
Increment
|
|
145
|
+
</button>
|
|
146
|
+
</div>
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
#### 函数式更新
|
|
152
|
+
|
|
153
|
+
```javascript
|
|
154
|
+
function Counter() {
|
|
155
|
+
const [count, setCount] = useState(0);
|
|
156
|
+
|
|
157
|
+
// ❌ 错误: 依赖当前状态
|
|
158
|
+
const incrementBad = () => {
|
|
159
|
+
setCount(count + 1);
|
|
160
|
+
setCount(count + 1); // 仍然是基于旧的 count
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
// ✅ 正确: 使用函数式更新
|
|
164
|
+
const incrementGood = () => {
|
|
165
|
+
setCount(prev => prev + 1);
|
|
166
|
+
setCount(prev => prev + 1); // 正确: prev 是最新状态
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
return (
|
|
170
|
+
<button onClick={incrementGood}>Count: {count}</button>
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
#### 惰性初始化
|
|
176
|
+
|
|
177
|
+
```javascript
|
|
178
|
+
function ExpensiveComponent() {
|
|
179
|
+
// ❌ 错误: 每次渲染都会执行 expensiveComputation
|
|
180
|
+
const [state, setState] = useState(expensiveComputation());
|
|
181
|
+
|
|
182
|
+
// ✅ 正确: 只在首次渲染时执行
|
|
183
|
+
const [state, setState] = useState(() => {
|
|
184
|
+
console.log('Lazy initialization');
|
|
185
|
+
return expensiveComputation();
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
return <div>{state}</div>;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function expensiveComputation() {
|
|
192
|
+
// 假设这是一个昂贵的计算
|
|
193
|
+
let result = 0;
|
|
194
|
+
for (let i = 0; i < 1000000; i++) {
|
|
195
|
+
result += i;
|
|
196
|
+
}
|
|
197
|
+
return result;
|
|
198
|
+
}
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
#### 对象和数组状态
|
|
202
|
+
|
|
203
|
+
```javascript
|
|
204
|
+
function UserProfile() {
|
|
205
|
+
const [user, setUser] = useState({
|
|
206
|
+
name: 'Alice',
|
|
207
|
+
age: 25,
|
|
208
|
+
email: 'alice@example.com'
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
// ❌ 错误: 直接修改状态
|
|
212
|
+
const updateNameBad = (newName) => {
|
|
213
|
+
user.name = newName;
|
|
214
|
+
setUser(user);
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
// ✅ 正确: 创建新对象
|
|
218
|
+
const updateNameGood = (newName) => {
|
|
219
|
+
setUser(prev => ({
|
|
220
|
+
...prev,
|
|
221
|
+
name: newName
|
|
222
|
+
}));
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
return (
|
|
226
|
+
<input
|
|
227
|
+
value={user.name}
|
|
228
|
+
onChange={(e) => updateNameGood(e.target.value)}
|
|
229
|
+
/>
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### 2. useEffect - 副作用处理
|
|
235
|
+
|
|
236
|
+
#### 基础用法
|
|
237
|
+
|
|
238
|
+
```javascript
|
|
239
|
+
import { useState, useEffect } from 'react';
|
|
240
|
+
|
|
241
|
+
function UserProfile({ userId }) {
|
|
242
|
+
const [user, setUser] = useState(null);
|
|
243
|
+
|
|
244
|
+
useEffect(() => {
|
|
245
|
+
// 副作用: 数据获取
|
|
246
|
+
fetchUser(userId).then(data => setUser(data));
|
|
247
|
+
|
|
248
|
+
// 清理函数 (可选)
|
|
249
|
+
return () => {
|
|
250
|
+
console.log('Cleanup before next effect or unmount');
|
|
251
|
+
};
|
|
252
|
+
}, [userId]); // 依赖数组
|
|
253
|
+
|
|
254
|
+
return user ? <div>{user.name}</div> : <div>Loading...</div>;
|
|
255
|
+
}
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
#### 依赖数组详解
|
|
259
|
+
|
|
260
|
+
```javascript
|
|
261
|
+
function Example({ userId, categoryId }) {
|
|
262
|
+
useEffect(() => {
|
|
263
|
+
console.log('Effect executed');
|
|
264
|
+
// 副作用代码
|
|
265
|
+
}, [userId, categoryId]); // 当 userId 或 categoryId 变化时执行
|
|
266
|
+
|
|
267
|
+
useEffect(() => {
|
|
268
|
+
console.log('Effect executed once');
|
|
269
|
+
// 空依赖数组: 只在挂载时执行一次
|
|
270
|
+
}, []);
|
|
271
|
+
|
|
272
|
+
useEffect(() => {
|
|
273
|
+
console.log('Effect executed every render');
|
|
274
|
+
// 无依赖数组: 每次渲染后都执行
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
#### 清理副作用
|
|
280
|
+
|
|
281
|
+
```javascript
|
|
282
|
+
function ChatRoom({ roomId }) {
|
|
283
|
+
const [messages, setMessages] = useState([]);
|
|
284
|
+
|
|
285
|
+
useEffect(() => {
|
|
286
|
+
const connection = createConnection(roomId);
|
|
287
|
+
|
|
288
|
+
// 订阅新消息
|
|
289
|
+
connection.on('message', (message) => {
|
|
290
|
+
setMessages(prev => [...prev, message]);
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
// 清理函数: 断开连接
|
|
294
|
+
return () => {
|
|
295
|
+
connection.disconnect();
|
|
296
|
+
};
|
|
297
|
+
}, [roomId]);
|
|
298
|
+
|
|
299
|
+
return (
|
|
300
|
+
<ul>
|
|
301
|
+
{messages.map(msg => <li key={msg.id}>{msg.text}</li>)}
|
|
302
|
+
</ul>
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
#### useEffect 的常见模式
|
|
308
|
+
|
|
309
|
+
```javascript
|
|
310
|
+
function DataFetcher({ url }) {
|
|
311
|
+
const [data, setData] = useState(null);
|
|
312
|
+
const [loading, setLoading] = useState(true);
|
|
313
|
+
const [error, setError] = useState(null);
|
|
314
|
+
|
|
315
|
+
useEffect(() => {
|
|
316
|
+
let cancelled = false;
|
|
317
|
+
|
|
318
|
+
async function fetchData() {
|
|
319
|
+
try {
|
|
320
|
+
setLoading(true);
|
|
321
|
+
setError(null);
|
|
322
|
+
|
|
323
|
+
const response = await fetch(url);
|
|
324
|
+
const result = await response.json();
|
|
325
|
+
|
|
326
|
+
if (!cancelled) {
|
|
327
|
+
setData(result);
|
|
328
|
+
}
|
|
329
|
+
} catch (err) {
|
|
330
|
+
if (!cancelled) {
|
|
331
|
+
setError(err.message);
|
|
332
|
+
}
|
|
333
|
+
} finally {
|
|
334
|
+
if (!cancelled) {
|
|
335
|
+
setLoading(false);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
fetchData();
|
|
341
|
+
|
|
342
|
+
return () => {
|
|
343
|
+
cancelled = true;
|
|
344
|
+
};
|
|
345
|
+
}, [url]);
|
|
346
|
+
|
|
347
|
+
if (loading) return <div>Loading...</div>;
|
|
348
|
+
if (error) return <div>Error: {error}</div>;
|
|
349
|
+
return <div>{JSON.stringify(data)}</div>;
|
|
350
|
+
}
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
### 3. useContext - 上下文消费
|
|
354
|
+
|
|
355
|
+
#### 基础用法
|
|
356
|
+
|
|
357
|
+
```javascript
|
|
358
|
+
import { createContext, useContext } from 'react';
|
|
359
|
+
|
|
360
|
+
// 创建 Context
|
|
361
|
+
const ThemeContext = createContext('light');
|
|
362
|
+
|
|
363
|
+
function App() {
|
|
364
|
+
return (
|
|
365
|
+
<ThemeContext.Provider value="dark">
|
|
366
|
+
<Toolbar />
|
|
367
|
+
</ThemeContext.Provider>
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function Toolbar() {
|
|
372
|
+
return <ThemedButton />;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function ThemedButton() {
|
|
376
|
+
// 使用 useContext 消费 Context
|
|
377
|
+
const theme = useContext(ThemeContext);
|
|
378
|
+
return <button className={theme}>Themed Button</button>;
|
|
379
|
+
}
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
#### Context + useState 模式
|
|
383
|
+
|
|
384
|
+
```javascript
|
|
385
|
+
import { createContext, useContext, useState } from 'react';
|
|
386
|
+
|
|
387
|
+
// 创建 Context
|
|
388
|
+
const UserContext = createContext(null);
|
|
389
|
+
|
|
390
|
+
function App() {
|
|
391
|
+
const [user, setUser] = useState(null);
|
|
392
|
+
|
|
393
|
+
return (
|
|
394
|
+
<UserContext.Provider value={{ user, setUser }}>
|
|
395
|
+
<UserProfile />
|
|
396
|
+
<LoginButton />
|
|
397
|
+
</UserContext.Provider>
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function UserProfile() {
|
|
402
|
+
const { user } = useContext(UserContext);
|
|
403
|
+
|
|
404
|
+
return user ? (
|
|
405
|
+
<div>Hello, {user.name}</div>
|
|
406
|
+
) : (
|
|
407
|
+
<div>Please log in</div>
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function LoginButton() {
|
|
412
|
+
const { user, setUser } = useContext(UserContext);
|
|
413
|
+
|
|
414
|
+
const handleLogin = () => {
|
|
415
|
+
setUser({ name: 'Alice', email: 'alice@example.com' });
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
const handleLogout = () => {
|
|
419
|
+
setUser(null);
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
return user ? (
|
|
423
|
+
<button onClick={handleLogout}>Logout</button>
|
|
424
|
+
) : (
|
|
425
|
+
<button onClick={handleLogin}>Login</button>
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
### 4. useReducer - 复杂状态管理
|
|
431
|
+
|
|
432
|
+
#### 基础用法
|
|
433
|
+
|
|
434
|
+
```javascript
|
|
435
|
+
import { useReducer } from 'react';
|
|
436
|
+
|
|
437
|
+
// Reducer 函数
|
|
438
|
+
function todoReducer(state, action) {
|
|
439
|
+
switch (action.type) {
|
|
440
|
+
case 'add':
|
|
441
|
+
return [...state, {
|
|
442
|
+
id: Date.now(),
|
|
443
|
+
text: action.text,
|
|
444
|
+
completed: false
|
|
445
|
+
}];
|
|
446
|
+
case 'toggle':
|
|
447
|
+
return state.map(todo =>
|
|
448
|
+
todo.id === action.id
|
|
449
|
+
? { ...todo, completed: !todo.completed }
|
|
450
|
+
: todo
|
|
451
|
+
);
|
|
452
|
+
case 'delete':
|
|
453
|
+
return state.filter(todo => todo.id !== action.id);
|
|
454
|
+
default:
|
|
455
|
+
throw new Error(`Unknown action: ${action.type}`);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function TodoList() {
|
|
460
|
+
const [todos, dispatch] = useReducer(todoReducer, []);
|
|
461
|
+
|
|
462
|
+
const addTodo = (text) => {
|
|
463
|
+
dispatch({ type: 'add', text });
|
|
464
|
+
};
|
|
465
|
+
|
|
466
|
+
const toggleTodo = (id) => {
|
|
467
|
+
dispatch({ type: 'toggle', id });
|
|
468
|
+
};
|
|
469
|
+
|
|
470
|
+
const deleteTodo = (id) => {
|
|
471
|
+
dispatch({ type: 'delete', id });
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
return (
|
|
475
|
+
<div>
|
|
476
|
+
<button onClick={() => addTodo('New Todo')}>Add</button>
|
|
477
|
+
<ul>
|
|
478
|
+
{todos.map(todo => (
|
|
479
|
+
<li key={todo.id}>
|
|
480
|
+
<span
|
|
481
|
+
onClick={() => toggleTodo(todo.id)}
|
|
482
|
+
style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}
|
|
483
|
+
>
|
|
484
|
+
{todo.text}
|
|
485
|
+
</span>
|
|
486
|
+
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
|
|
487
|
+
</li>
|
|
488
|
+
))}
|
|
489
|
+
</ul>
|
|
490
|
+
</div>
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
```
|
|
494
|
+
|
|
495
|
+
#### 惰性初始化
|
|
496
|
+
|
|
497
|
+
```javascript
|
|
498
|
+
function TodoList({ initialTodos }) {
|
|
499
|
+
// 惰性初始化
|
|
500
|
+
const [todos, dispatch] = useReducer(
|
|
501
|
+
todoReducer,
|
|
502
|
+
initialTodos,
|
|
503
|
+
(initial) => {
|
|
504
|
+
// 可以在这里执行昂贵的初始化逻辑
|
|
505
|
+
return initial.filter(todo => !todo.deleted);
|
|
506
|
+
}
|
|
507
|
+
);
|
|
508
|
+
|
|
509
|
+
// ...
|
|
510
|
+
}
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
### 5. useMemo - 性能优化
|
|
514
|
+
|
|
515
|
+
#### 基础用法
|
|
516
|
+
|
|
517
|
+
```javascript
|
|
518
|
+
import { useMemo } from 'react';
|
|
519
|
+
|
|
520
|
+
function ExpensiveComponent({ items, filter }) {
|
|
521
|
+
// ❌ 错误: 每次渲染都执行昂贵计算
|
|
522
|
+
const filteredItems = items.filter(filter).map(expensiveTransformation);
|
|
523
|
+
|
|
524
|
+
// ✅ 正确: 使用 useMemo 缓存结果
|
|
525
|
+
const filteredItems = useMemo(() => {
|
|
526
|
+
console.log('Recalculating...');
|
|
527
|
+
return items.filter(filter).map(expensiveTransformation);
|
|
528
|
+
}, [items, filter]);
|
|
529
|
+
|
|
530
|
+
return (
|
|
531
|
+
<ul>
|
|
532
|
+
{filteredItems.map(item => <li key={item.id}>{item.name}</li>)}
|
|
533
|
+
</ul>
|
|
534
|
+
);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function expensiveTransformation(item) {
|
|
538
|
+
// 假设这是一个昂贵的转换
|
|
539
|
+
let result = item;
|
|
540
|
+
for (let i = 0; i < 1000; i++) {
|
|
541
|
+
result = { ...result, score: (result.score || 0) + i };
|
|
542
|
+
}
|
|
543
|
+
return result;
|
|
544
|
+
}
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
#### 引用相等性优化
|
|
548
|
+
|
|
549
|
+
```javascript
|
|
550
|
+
function ParentComponent() {
|
|
551
|
+
const [count, setCount] = useState(0);
|
|
552
|
+
const items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
|
|
553
|
+
|
|
554
|
+
// ❌ 错误: 每次渲染都创建新数组
|
|
555
|
+
// const sortedItems = items.sort((a, b) => a.name.localeCompare(b.name));
|
|
556
|
+
|
|
557
|
+
// ✅ 正确: 使用 useMemo 保持引用相等
|
|
558
|
+
const sortedItems = useMemo(
|
|
559
|
+
() => items.sort((a, b) => a.name.localeCompare(b.name)),
|
|
560
|
+
[items]
|
|
561
|
+
);
|
|
562
|
+
|
|
563
|
+
return (
|
|
564
|
+
<div>
|
|
565
|
+
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
|
|
566
|
+
<ChildComponent items={sortedItems} />
|
|
567
|
+
</div>
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// 使用 React.memo 优化子组件
|
|
572
|
+
const ChildComponent = React.memo(({ items }) => {
|
|
573
|
+
console.log('ChildComponent rendered');
|
|
574
|
+
return <div>{items.length} items</div>;
|
|
575
|
+
});
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
### 6. useCallback - 函数缓存
|
|
579
|
+
|
|
580
|
+
#### 基础用法
|
|
581
|
+
|
|
582
|
+
```javascript
|
|
583
|
+
import { useState, useCallback } from 'react';
|
|
584
|
+
|
|
585
|
+
function ParentComponent() {
|
|
586
|
+
const [count, setCount] = useState(0);
|
|
587
|
+
const [items, setItems] = useState([]);
|
|
588
|
+
|
|
589
|
+
// ❌ 错误: 每次渲染都创建新函数
|
|
590
|
+
// const handleClick = () => {
|
|
591
|
+
// console.log('Clicked');
|
|
592
|
+
// };
|
|
593
|
+
|
|
594
|
+
// ✅ 正确: 使用 useCallback 缓存函数
|
|
595
|
+
const handleClick = useCallback(() => {
|
|
596
|
+
console.log('Clicked');
|
|
597
|
+
}, []);
|
|
598
|
+
|
|
599
|
+
const addItem = useCallback((item) => {
|
|
600
|
+
setItems(prev => [...prev, item]);
|
|
601
|
+
}, []);
|
|
602
|
+
|
|
603
|
+
return (
|
|
604
|
+
<div>
|
|
605
|
+
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
|
|
606
|
+
<ChildComponent onClick={handleClick} onAdd={addItem} />
|
|
607
|
+
</div>
|
|
608
|
+
);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// 使用 React.memo 优化
|
|
612
|
+
const ChildComponent = React.memo(({ onClick, onAdd }) => {
|
|
613
|
+
console.log('ChildComponent rendered');
|
|
614
|
+
return (
|
|
615
|
+
<div>
|
|
616
|
+
<button onClick={onClick}>Click me</button>
|
|
617
|
+
<button onClick={() => onAdd({ id: Date.now() })}>Add item</button>
|
|
618
|
+
</div>
|
|
619
|
+
);
|
|
620
|
+
});
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
## 自定义 Hooks
|
|
624
|
+
|
|
625
|
+
### 1. useLocalStorage - 持久化状态
|
|
626
|
+
|
|
627
|
+
```javascript
|
|
628
|
+
import { useState, useEffect } from 'react';
|
|
629
|
+
|
|
630
|
+
function useLocalStorage(key, initialValue) {
|
|
631
|
+
// 惰性初始化
|
|
632
|
+
const [storedValue, setStoredValue] = useState(() => {
|
|
633
|
+
try {
|
|
634
|
+
const item = window.localStorage.getItem(key);
|
|
635
|
+
return item ? JSON.parse(item) : initialValue;
|
|
636
|
+
} catch (error) {
|
|
637
|
+
console.error(error);
|
|
638
|
+
return initialValue;
|
|
639
|
+
}
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
// 返回包装函数
|
|
643
|
+
const setValue = useCallback((value) => {
|
|
644
|
+
try {
|
|
645
|
+
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
|
646
|
+
setStoredValue(valueToStore);
|
|
647
|
+
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
|
648
|
+
} catch (error) {
|
|
649
|
+
console.error(error);
|
|
650
|
+
}
|
|
651
|
+
}, [key, storedValue]);
|
|
652
|
+
|
|
653
|
+
return [storedValue, setValue];
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
// 使用示例
|
|
657
|
+
function App() {
|
|
658
|
+
const [name, setName] = useLocalStorage('name', 'Alice');
|
|
659
|
+
|
|
660
|
+
return (
|
|
661
|
+
<input
|
|
662
|
+
value={name}
|
|
663
|
+
onChange={(e) => setName(e.target.value)}
|
|
664
|
+
placeholder="Enter your name"
|
|
665
|
+
/>
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
### 2. useFetch - 数据获取
|
|
671
|
+
|
|
672
|
+
```javascript
|
|
673
|
+
import { useState, useEffect } from 'react';
|
|
674
|
+
|
|
675
|
+
function useFetch(url) {
|
|
676
|
+
const [data, setData] = useState(null);
|
|
677
|
+
const [loading, setLoading] = useState(true);
|
|
678
|
+
const [error, setError] = useState(null);
|
|
679
|
+
|
|
680
|
+
useEffect(() => {
|
|
681
|
+
let cancelled = false;
|
|
682
|
+
|
|
683
|
+
async function fetchData() {
|
|
684
|
+
try {
|
|
685
|
+
setLoading(true);
|
|
686
|
+
setError(null);
|
|
687
|
+
|
|
688
|
+
const response = await fetch(url);
|
|
689
|
+
if (!response.ok) {
|
|
690
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
const result = await response.json();
|
|
694
|
+
|
|
695
|
+
if (!cancelled) {
|
|
696
|
+
setData(result);
|
|
697
|
+
}
|
|
698
|
+
} catch (err) {
|
|
699
|
+
if (!cancelled) {
|
|
700
|
+
setError(err.message);
|
|
701
|
+
}
|
|
702
|
+
} finally {
|
|
703
|
+
if (!cancelled) {
|
|
704
|
+
setLoading(false);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
fetchData();
|
|
710
|
+
|
|
711
|
+
return () => {
|
|
712
|
+
cancelled = true;
|
|
713
|
+
};
|
|
714
|
+
}, [url]);
|
|
715
|
+
|
|
716
|
+
return { data, loading, error };
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// 使用示例
|
|
720
|
+
function UserProfile({ userId }) {
|
|
721
|
+
const { data: user, loading, error } = useFetch(
|
|
722
|
+
`https://api.example.com/users/${userId}`
|
|
723
|
+
);
|
|
724
|
+
|
|
725
|
+
if (loading) return <div>Loading...</div>;
|
|
726
|
+
if (error) return <div>Error: {error}</div>;
|
|
727
|
+
|
|
728
|
+
return (
|
|
729
|
+
<div>
|
|
730
|
+
<h1>{user.name}</h1>
|
|
731
|
+
<p>{user.email}</p>
|
|
732
|
+
</div>
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
```
|
|
736
|
+
|
|
737
|
+
### 3. useDebounce - 防抖
|
|
738
|
+
|
|
739
|
+
```javascript
|
|
740
|
+
import { useState, useEffect } from 'react';
|
|
741
|
+
|
|
742
|
+
function useDebounce(value, delay) {
|
|
743
|
+
const [debouncedValue, setDebouncedValue] = useState(value);
|
|
744
|
+
|
|
745
|
+
useEffect(() => {
|
|
746
|
+
const handler = setTimeout(() => {
|
|
747
|
+
setDebouncedValue(value);
|
|
748
|
+
}, delay);
|
|
749
|
+
|
|
750
|
+
return () => {
|
|
751
|
+
clearTimeout(handler);
|
|
752
|
+
};
|
|
753
|
+
}, [value, delay]);
|
|
754
|
+
|
|
755
|
+
return debouncedValue;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// 使用示例
|
|
759
|
+
function SearchInput() {
|
|
760
|
+
const [searchTerm, setSearchTerm] = useState('');
|
|
761
|
+
const debouncedSearchTerm = useDebounce(searchTerm, 500);
|
|
762
|
+
|
|
763
|
+
useEffect(() => {
|
|
764
|
+
if (debouncedSearchTerm) {
|
|
765
|
+
// 执行搜索
|
|
766
|
+
console.log('Searching for:', debouncedSearchTerm);
|
|
767
|
+
}
|
|
768
|
+
}, [debouncedSearchTerm]);
|
|
769
|
+
|
|
770
|
+
return (
|
|
771
|
+
<input
|
|
772
|
+
value={searchTerm}
|
|
773
|
+
onChange={(e) => setSearchTerm(e.target.value)}
|
|
774
|
+
placeholder="Search..."
|
|
775
|
+
/>
|
|
776
|
+
);
|
|
777
|
+
}
|
|
778
|
+
```
|
|
779
|
+
|
|
780
|
+
### 4. useWindowSize - 响应式设计
|
|
781
|
+
|
|
782
|
+
```javascript
|
|
783
|
+
import { useState, useEffect } from 'react';
|
|
784
|
+
|
|
785
|
+
function useWindowSize() {
|
|
786
|
+
const [windowSize, setWindowSize] = useState({
|
|
787
|
+
width: typeof window !== 'undefined' ? window.innerWidth : 0,
|
|
788
|
+
height: typeof window !== 'undefined' ? window.innerHeight : 0
|
|
789
|
+
});
|
|
790
|
+
|
|
791
|
+
useEffect(() => {
|
|
792
|
+
function handleResize() {
|
|
793
|
+
setWindowSize({
|
|
794
|
+
width: window.innerWidth,
|
|
795
|
+
height: window.innerHeight
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
window.addEventListener('resize', handleResize);
|
|
800
|
+
|
|
801
|
+
// 立即调用一次
|
|
802
|
+
handleResize();
|
|
803
|
+
|
|
804
|
+
return () => {
|
|
805
|
+
window.removeEventListener('resize', handleResize);
|
|
806
|
+
};
|
|
807
|
+
}, []);
|
|
808
|
+
|
|
809
|
+
return windowSize;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// 使用示例
|
|
813
|
+
function ResponsiveComponent() {
|
|
814
|
+
const { width, height } = useWindowSize();
|
|
815
|
+
|
|
816
|
+
return (
|
|
817
|
+
<div>
|
|
818
|
+
<p>Width: {width}px</p>
|
|
819
|
+
<p>Height: {height}px</p>
|
|
820
|
+
{width < 768 ? <MobileLayout /> : <DesktopLayout />}
|
|
821
|
+
</div>
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
```
|
|
825
|
+
|
|
826
|
+
### 5. usePrevious - 获取前一个值
|
|
827
|
+
|
|
828
|
+
```javascript
|
|
829
|
+
import { useRef, useEffect } from 'react';
|
|
830
|
+
|
|
831
|
+
function usePrevious(value) {
|
|
832
|
+
const ref = useRef();
|
|
833
|
+
|
|
834
|
+
useEffect(() => {
|
|
835
|
+
ref.current = value;
|
|
836
|
+
}, [value]);
|
|
837
|
+
|
|
838
|
+
return ref.current;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// 使用示例
|
|
842
|
+
function Counter() {
|
|
843
|
+
const [count, setCount] = useState(0);
|
|
844
|
+
const prevCount = usePrevious(count);
|
|
845
|
+
|
|
846
|
+
return (
|
|
847
|
+
<div>
|
|
848
|
+
<p>Current: {count}</p>
|
|
849
|
+
<p>Previous: {prevCount}</p>
|
|
850
|
+
<button onClick={() => setCount(count + 1)}>Increment</button>
|
|
851
|
+
</div>
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
```
|
|
855
|
+
|
|
856
|
+
## 最佳实践
|
|
857
|
+
|
|
858
|
+
### 1. 正确设置依赖项
|
|
859
|
+
|
|
860
|
+
```javascript
|
|
861
|
+
function Example({ userId }) {
|
|
862
|
+
const [data, setData] = useState(null);
|
|
863
|
+
|
|
864
|
+
// ❌ 错误: 缺少依赖
|
|
865
|
+
useEffect(() => {
|
|
866
|
+
fetchUser(userId).then(setData);
|
|
867
|
+
}, []); // userId 应该在依赖中
|
|
868
|
+
|
|
869
|
+
// ✅ 正确: 包含所有依赖
|
|
870
|
+
useEffect(() => {
|
|
871
|
+
fetchUser(userId).then(setData);
|
|
872
|
+
}, [userId]);
|
|
873
|
+
|
|
874
|
+
// 或者使用 eslint 插件
|
|
875
|
+
// npm install eslint-plugin-react-hooks --save-dev
|
|
876
|
+
}
|
|
877
|
+
```
|
|
878
|
+
|
|
879
|
+
### 2. 避免过度优化
|
|
880
|
+
|
|
881
|
+
```javascript
|
|
882
|
+
function Example({ items }) {
|
|
883
|
+
// ❌ 错误: 过度优化,简单计算不需要 useMemo
|
|
884
|
+
const count = useMemo(() => items.length, [items]);
|
|
885
|
+
|
|
886
|
+
// ✅ 正确: 简单计算直接执行
|
|
887
|
+
const count = items.length;
|
|
888
|
+
|
|
889
|
+
// ✅ 正确: 复杂计算使用 useMemo
|
|
890
|
+
const sortedItems = useMemo(
|
|
891
|
+
() => items.filter(item => item.active).sort((a, b) => a.name.localeCompare(b.name)),
|
|
892
|
+
[items]
|
|
893
|
+
);
|
|
894
|
+
|
|
895
|
+
return <div>{count}</div>;
|
|
896
|
+
}
|
|
897
|
+
```
|
|
898
|
+
|
|
899
|
+
### 3. 合理拆分 Effects
|
|
900
|
+
|
|
901
|
+
```javascript
|
|
902
|
+
function Example({ userId, productId }) {
|
|
903
|
+
// ❌ 错误: 不相关的逻辑混在一起
|
|
904
|
+
useEffect(() => {
|
|
905
|
+
fetchUser(userId);
|
|
906
|
+
fetchProduct(productId);
|
|
907
|
+
trackPageView();
|
|
908
|
+
}, [userId, productId]);
|
|
909
|
+
|
|
910
|
+
// ✅ 正确: 拆分为多个 Effects
|
|
911
|
+
useEffect(() => {
|
|
912
|
+
fetchUser(userId);
|
|
913
|
+
}, [userId]);
|
|
914
|
+
|
|
915
|
+
useEffect(() => {
|
|
916
|
+
fetchProduct(productId);
|
|
917
|
+
}, [productId]);
|
|
918
|
+
|
|
919
|
+
useEffect(() => {
|
|
920
|
+
trackPageView();
|
|
921
|
+
}, []); // 只在挂载时执行一次
|
|
922
|
+
}
|
|
923
|
+
```
|
|
924
|
+
|
|
925
|
+
### 4. 使用自定义 Hooks 提取逻辑
|
|
926
|
+
|
|
927
|
+
```javascript
|
|
928
|
+
function UserProfile({ userId }) {
|
|
929
|
+
// ❌ 错误: 逻辑分散在组件中
|
|
930
|
+
const [user, setUser] = useState(null);
|
|
931
|
+
const [loading, setLoading] = useState(true);
|
|
932
|
+
const [error, setError] = useState(null);
|
|
933
|
+
|
|
934
|
+
useEffect(() => {
|
|
935
|
+
// ... fetch logic
|
|
936
|
+
}, [userId]);
|
|
937
|
+
|
|
938
|
+
// ✅ 正确: 使用自定义 Hook
|
|
939
|
+
const { user, loading, error } = useUser(userId);
|
|
940
|
+
|
|
941
|
+
if (loading) return <div>Loading...</div>;
|
|
942
|
+
if (error) return <div>Error: {error}</div>;
|
|
943
|
+
|
|
944
|
+
return <div>{user.name}</div>;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// 自定义 Hook
|
|
948
|
+
function useUser(userId) {
|
|
949
|
+
const [user, setUser] = useState(null);
|
|
950
|
+
const [loading, setLoading] = useState(true);
|
|
951
|
+
const [error, setError] = useState(null);
|
|
952
|
+
|
|
953
|
+
useEffect(() => {
|
|
954
|
+
let cancelled = false;
|
|
955
|
+
|
|
956
|
+
async function fetchUser() {
|
|
957
|
+
try {
|
|
958
|
+
setLoading(true);
|
|
959
|
+
setError(null);
|
|
960
|
+
|
|
961
|
+
const response = await fetch(`/api/users/${userId}`);
|
|
962
|
+
const data = await response.json();
|
|
963
|
+
|
|
964
|
+
if (!cancelled) {
|
|
965
|
+
setUser(data);
|
|
966
|
+
}
|
|
967
|
+
} catch (err) {
|
|
968
|
+
if (!cancelled) {
|
|
969
|
+
setError(err.message);
|
|
970
|
+
}
|
|
971
|
+
} finally {
|
|
972
|
+
if (!cancelled) {
|
|
973
|
+
setLoading(false);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
fetchUser();
|
|
979
|
+
|
|
980
|
+
return () => {
|
|
981
|
+
cancelled = true;
|
|
982
|
+
};
|
|
983
|
+
}, [userId]);
|
|
984
|
+
|
|
985
|
+
return { user, loading, error };
|
|
986
|
+
}
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
## 常见陷阱
|
|
990
|
+
|
|
991
|
+
### 1. 闭包陷阱
|
|
992
|
+
|
|
993
|
+
```javascript
|
|
994
|
+
function Counter() {
|
|
995
|
+
const [count, setCount] = useState(0);
|
|
996
|
+
|
|
997
|
+
useEffect(() => {
|
|
998
|
+
const id = setInterval(() => {
|
|
999
|
+
// ❌ 错误: count 永远是初始值 0
|
|
1000
|
+
console.log(count);
|
|
1001
|
+
}, 1000);
|
|
1002
|
+
|
|
1003
|
+
return () => clearInterval(id);
|
|
1004
|
+
}, []); // 空依赖
|
|
1005
|
+
|
|
1006
|
+
useEffect(() => {
|
|
1007
|
+
const id = setInterval(() => {
|
|
1008
|
+
// ✅ 正确: 使用函数式更新
|
|
1009
|
+
setCount(prev => {
|
|
1010
|
+
console.log(prev);
|
|
1011
|
+
return prev + 1;
|
|
1012
|
+
});
|
|
1013
|
+
}, 1000);
|
|
1014
|
+
|
|
1015
|
+
return () => clearInterval(id);
|
|
1016
|
+
}, []);
|
|
1017
|
+
|
|
1018
|
+
return <div>{count}</div>;
|
|
1019
|
+
}
|
|
1020
|
+
```
|
|
1021
|
+
|
|
1022
|
+
### 2. 竞态条件
|
|
1023
|
+
|
|
1024
|
+
```javascript
|
|
1025
|
+
function SearchResults({ query }) {
|
|
1026
|
+
const [results, setResults] = useState([]);
|
|
1027
|
+
|
|
1028
|
+
useEffect(() => {
|
|
1029
|
+
// ❌ 错误: 可能出现竞态条件
|
|
1030
|
+
fetch(`/api/search?q=${query}`)
|
|
1031
|
+
.then(res => res.json())
|
|
1032
|
+
.then(setResults);
|
|
1033
|
+
}, [query]);
|
|
1034
|
+
|
|
1035
|
+
useEffect(() => {
|
|
1036
|
+
// ✅ 正确: 使用清理函数
|
|
1037
|
+
let cancelled = false;
|
|
1038
|
+
|
|
1039
|
+
fetch(`/api/search?q=${query}`)
|
|
1040
|
+
.then(res => res.json())
|
|
1041
|
+
.then(data => {
|
|
1042
|
+
if (!cancelled) {
|
|
1043
|
+
setResults(data);
|
|
1044
|
+
}
|
|
1045
|
+
});
|
|
1046
|
+
|
|
1047
|
+
return () => {
|
|
1048
|
+
cancelled = true;
|
|
1049
|
+
};
|
|
1050
|
+
}, [query]);
|
|
1051
|
+
|
|
1052
|
+
return <div>{results.length} results</div>;
|
|
1053
|
+
}
|
|
1054
|
+
```
|
|
1055
|
+
|
|
1056
|
+
### 3. 无限循环
|
|
1057
|
+
|
|
1058
|
+
```javascript
|
|
1059
|
+
function Example() {
|
|
1060
|
+
const [count, setCount] = useState(0);
|
|
1061
|
+
|
|
1062
|
+
// ❌ 错误: 无限循环
|
|
1063
|
+
useEffect(() => {
|
|
1064
|
+
setCount(count + 1);
|
|
1065
|
+
}, [count]);
|
|
1066
|
+
|
|
1067
|
+
// ✅ 正确: 使用函数式更新
|
|
1068
|
+
useEffect(() => {
|
|
1069
|
+
setCount(prev => prev + 1);
|
|
1070
|
+
}, []); // 空依赖,只在挂载时执行一次
|
|
1071
|
+
|
|
1072
|
+
return <div>{count}</div>;
|
|
1073
|
+
}
|
|
1074
|
+
```
|
|
1075
|
+
|
|
1076
|
+
## 参考资料
|
|
1077
|
+
|
|
1078
|
+
### 官方文档
|
|
1079
|
+
- [React Hooks 官方文档](https://react.dev/reference/react)
|
|
1080
|
+
- [React Hooks FAQ](https://react.dev/reference/react/hooks)
|
|
1081
|
+
- [Rules of Hooks](https://react.dev/warnings/invalid-hook-call-warning.html)
|
|
1082
|
+
|
|
1083
|
+
### 教程和文章
|
|
1084
|
+
- [Making Sense of React Hooks](https://medium.com/@dan_abramov/making-setstate-declarative-with-react-hooks-4d13c2cc5d3d)
|
|
1085
|
+
- [A Complete Guide to useEffect](https://overreacted.io/a-complete-guide-to-useeffect/)
|
|
1086
|
+
- [React Hooks: Not Magic, Just Arrays](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1fa16c1b)
|
|
1087
|
+
|
|
1088
|
+
### 工具
|
|
1089
|
+
- [eslint-plugin-react-hooks](https://www.npmjs.com/package/eslint-plugin-react-hooks)
|
|
1090
|
+
- [React Developer Tools](https://react.dev/learn/react-developer-tools)
|
|
1091
|
+
|
|
1092
|
+
---
|
|
1093
|
+
|
|
1094
|
+
**知识ID**: `react-hooks-complete-guide`
|
|
1095
|
+
**领域**: frontend
|
|
1096
|
+
**类型**: standards
|
|
1097
|
+
**难度**: intermediate
|
|
1098
|
+
**质量分**: 93
|
|
1099
|
+
**维护者**: frontend-team@umadev.com
|
|
1100
|
+
**最后更新**: 2026-03-29
|