React 的规则

就像不同的编程语言有自己表达概念的方式一样,React 也有自己的惯用语——或者说规则——来表达模式,使其易于理解并能够生成高质量的应用。


注意

要了解更多关于使用 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 调用组件和钩子

🌐 React calls Components and Hooks

React 负责在必要时渲染组件和钩子,以优化用户体验。 它是声明式的:你告诉 React 在组件逻辑中渲染什么,React 会决定如何最好地向用户显示它。


钩子的规则

🌐 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.