React 的规则

正如不同的编程语言有自己的表达概念的方式一样,React 有自己的习惯用法或规则,用于如何以易于理解的方式表达模式并产生高质量的应用。

¥Just as different programming languages have their own ways of expressing concepts, React has its own idioms — or rules — for how to express patterns in a way that is easy to understand and yields high-quality applications.


注意

要了解有关使用 React 表达 UI 的更多信息,我们建议阅读 在 React 中思考

¥To learn more about expressing UIs with React, we recommend reading Thinking in 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 自动优化你的代码。

¥Purity in Components and Hooks is a key rule of React that makes your app predictable, easy to debug, and allows React to automatically optimize your code.


React 调用组件和钩子

¥React calls Components and Hooks

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

¥React is responsible for rendering components and hooks when necessary to optimize the user experience. It is declarative: you tell React what to render in your component’s logic, and React will figure out how best to display it to your user.


钩子的规则

¥Rules of Hooks

钩子是使用 JavaScript 函数定义的,但它们代表一种特殊类型的可重用 UI 逻辑,并且对调用位置有限制。使用时需遵循 钩子的规则

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


React 中文网 - 粤ICP备13048890号