React 的规则
就像不同的编程语言有自己表达概念的方式一样,React 也有自己的惯用语——或者说规则——来表达模式,使其易于理解并能够生成高质量的应用。
本节描述了编写地道 React 代码时需要遵循的规则。编写地道的 React 代码可以帮助你编写结构良好、安全且可组合的应用。这些特性使你的应用对变化更具弹性,并且更容易与其他开发者、库和工具协作。
🌐 This section describes the rules you need to follow to write idiomatic React code. Writing idiomatic React code can help you write well organized, safe, and composable applications. These properties make your app more resilient to changes and makes it easier to work with other developers, libraries, and tools.
这些规则被称为React规则。它们是规则——而不仅仅是指导方针——因为如果违反这些规则,你的应用很可能会出现错误。你的代码也会变得不符合习惯,更难理解和推断。
🌐 These rules are known as the Rules of React. They are rules – and not just guidelines – in the sense that if they are broken, your app likely has bugs. Your code also becomes unidiomatic and harder to understand and reason about.
我们强烈建议在使用 React 的 ESLint 插件 的同时使用 严格模式,以帮助你的代码库遵循 React 规则。通过遵循 React 规则,你将能够发现和解决这些错误,并保持你的应用可维护。
🌐 We strongly recommend using Strict Mode alongside React’s ESLint plugin to help your codebase follow the Rules of React. By following the Rules of React, you’ll be able to find and address these bugs and keep your application maintainable.
组件和钩子必须是纯的
🌐 Components and Hooks must be pure
组件和钩子的纯粹性 是 React 的一条关键规则,它使你的应用可预测、易于调试,并允许 React 自动优化你的代码。
- 组件必须是幂等的 – React 组件被假定总是根据其输入(props、state 和 context)返回相同的输出。
- 副作用必须在渲染之外运行 – 副作用不应在渲染中运行,因为 React 可能会多次渲染组件以创建最佳的用户体验。
- Props 和 state 是不可变的 – 一个组件的 props 和 state 对于单次渲染来说是不可变的快照。切勿直接修改它们。
- 传递给 Hooks 的返回值和参数是不可变的 – 一旦值被传递给 Hook,你就不应该修改它们。就像 JSX 中的 props 一样,值在传递给 Hook 时会变得不可变。
- 传递给 JSX 的值是不可变的 – 在值被用于 JSX 之后不要修改它们。在创建 JSX 之前进行修改。
React 调用组件和钩子
🌐 React calls Components and Hooks
React 负责在必要时渲染组件和钩子,以优化用户体验。 它是声明式的:你告诉 React 在组件逻辑中渲染什么,React 会决定如何最好地向用户显示它。
- 永远不要直接调用组件函数 – 组件应该只在 JSX 中使用。不要像普通函数一样调用它们。
- 永远不要将 Hooks 当作普通值传递 – Hooks 应该只在组件内部调用。永远不要将其作为普通值传递。
钩子的规则
🌐 Rules of Hooks
Hooks 是使用 JavaScript 函数定义的,但它们代表一种具有调用位置限制的可重用 UI 逻辑特殊类型。在使用它们时,你需要遵循 Hooks 规则。
🌐 Hooks are defined using JavaScript functions, but they represent a special type of reusable UI logic with restrictions on where they can be called. You need to follow the Rules of Hooks when using them.
- 只在顶层调用 Hooks – 不要在循环、条件或嵌套函数内部调用 Hooks。相反,应始终在 React 函数的顶层使用 Hooks,在任何提前返回之前。
- 仅从 React 函数组件中调用 Hooks – 不要从普通的 JavaScript 函数中调用 Hooks。