From 415155ab47d3723701fb140d2d61676c1e7d6de1 Mon Sep 17 00:00:00 2001 From: Yucohny Date: Fri, 14 Jul 2023 11:17:46 +0800 Subject: [PATCH] docs(cn): translate learn/synchronizing-with-effects --- .../learn/synchronizing-with-effects.md | 556 +++++++++--------- 1 file changed, 278 insertions(+), 278 deletions(-) diff --git a/src/content/learn/synchronizing-with-effects.md b/src/content/learn/synchronizing-with-effects.md index 1641ef7b9c..fd4a321025 100644 --- a/src/content/learn/synchronizing-with-effects.md +++ b/src/content/learn/synchronizing-with-effects.md @@ -1,97 +1,97 @@ --- -title: 'Synchronizing with Effects' +title: '与 Effect 同步' --- -Some components need to synchronize with external systems. For example, you might want to control a non-React component based on the React state, set up a server connection, or send an analytics log when a component appears on the screen. *Effects* let you run some code after rendering so that you can synchronize your component with some system outside of React. +有些组件需要与外部系统同步。例如,你可能希望根据 React state 控制非 React 组件、设置服务器连接或在组件出现在屏幕上时发送分析日志。Effects 会在渲染后运行一些代码,以便可以将组件与 React 之外的某些系统同步。 -- What Effects are -- How Effects are different from events -- How to declare an Effect in your component -- How to skip re-running an Effect unnecessarily -- Why Effects run twice in development and how to fix them +- 什么是 Effect +- Effect 与事件(event)有何不同 +- 如何在组件中声明 Effect +- 如何避免不必要地重新运行 Effect +- 为什么 Effect 在开发环境中会影响两次,如何修复它们 -## What are Effects and how are they different from events? {/*what-are-effects-and-how-are-they-different-from-events*/} +## 什么是 Effect,它与事件(event)有何不同? {/*what-are-effects-and-how-are-they-different-from-events*/} -Before getting to Effects, you need to be familiar with two types of logic inside React components: +在谈到 Effect 之前,你需要熟悉 React 组件中的两种逻辑类型: -- **Rendering code** (introduced in [Describing the UI](/learn/describing-the-ui)) lives at the top level of your component. This is where you take the props and state, transform them, and return the JSX you want to see on the screen. [Rendering code must be pure.](/learn/keeping-components-pure) Like a math formula, it should only _calculate_ the result, but not do anything else. +- **渲染逻辑代码**(在 [描述 UI](/learn/describing-the-ui) 中有介绍)位于组件的顶层。你将在这里接收 props 和 state,并对它们进行转换,最终返回你想在屏幕上看到的 JSX。[渲染的代码必须是纯粹的](/learn/keeping-components-pure)——就像数学公式一样,它只应该“计算”结果,而不做其他任何事情。 -- **Event handlers** (introduced in [Adding Interactivity](/learn/adding-interactivity)) are nested functions inside your components that *do* things rather than just calculate them. An event handler might update an input field, submit an HTTP POST request to buy a product, or navigate the user to another screen. Event handlers contain ["side effects"](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) (they change the program's state) caused by a specific user action (for example, a button click or typing). +- **事件处理程序**(在 [添加交互性](/learn/adding-interactivity) 中介绍)是嵌套在组件内部的函数,而不仅仅是计算函数。事件处理程序可能会更新输入字段、提交 HTTP POST 请求以购买产品,或者将用户导航到另一个屏幕。事件处理程序包含由特定用户操作(例如按钮点击或键入)引起的“副作用”(它们改变了程序的状态)。 -Sometimes this isn't enough. Consider a `ChatRoom` component that must connect to the chat server whenever it's visible on the screen. Connecting to a server is not a pure calculation (it's a side effect) so it can't happen during rendering. However, there is no single particular event like a click that causes `ChatRoom` to be displayed. +有时这还不够。考虑一个 `ChatRoom` 组件,它在屏幕上可见时必须连接到聊天服务器。连接到服务器不是一个纯计算(它包含副作用),因此它不能在渲染过程中发生。然而,并没有一个特定的事件(比如点击)导致 `ChatRoom` 被显示。 -***Effects* let you specify side effects that are caused by rendering itself, rather than by a particular event.** Sending a message in the chat is an *event* because it is directly caused by the user clicking a specific button. However, setting up a server connection is an *Effect* because it should happen no matter which interaction caused the component to appear. Effects run at the end of a [commit](/learn/render-and-commit) after the screen updates. This is a good time to synchronize the React components with some external system (like network or a third-party library). +**Effect 允许你指定由渲染本身,而不是特定事件引起的副作用**。在聊天中发送消息是一个“事件”,因为它直接由用户点击特定按钮引起。然而,建立服务器连接是 Effect,因为它应该发生无论哪种交互导致组件出现。Effect 在屏幕更新后的 [提交阶段](/learn/render-and-commit) 运行。这是一个很好的时机,可以将 React 组件与某个外部系统(如网络或第三方库)同步。 -Here and later in this text, capitalized "Effect" refers to the React-specific definition above, i.e. a side effect caused by rendering. To refer to the broader programming concept, we'll say "side effect". +在本文和后续文本中,`Effect` 在 React 中是专有定义——由渲染引起的副作用。为了指代更广泛的编程概念,也可以将其称为“副作用(side effect)”。 -## You might not need an Effect {/*you-might-not-need-an-effect*/} +## 你可能不需要 Effect {/*you-might-not-need-an-effect*/} -**Don't rush to add Effects to your components.** Keep in mind that Effects are typically used to "step out" of your React code and synchronize with some *external* system. This includes browser APIs, third-party widgets, network, and so on. If your Effect only adjusts some state based on other state, [you might not need an Effect.](/learn/you-might-not-need-an-effect) +**不要随意在你的组件中使用 Effect**。记住,Effect 通常用于暂时“跳出” React 代码并与一些 **外部** 系统进行同步。这包括浏览器 API、第三方小部件,以及网络等等。如果你想用 Effect 仅根据其他状态调整某些状态,那么 [你可能不需要 Effect](/learn/you-might-not-need-an-effect)。 -## How to write an Effect {/*how-to-write-an-effect*/} +## 如何编写 Effect {/*how-to-write-an-effect*/} -To write an Effect, follow these three steps: +编写 Effect 需要遵循以下三个规则: -1. **Declare an Effect.** By default, your Effect will run after every render. -2. **Specify the Effect dependencies.** Most Effects should only re-run *when needed* rather than after every render. For example, a fade-in animation should only trigger when a component appears. Connecting and disconnecting to a chat room should only happen when the component appears and disappears, or when the chat room changes. You will learn how to control this by specifying *dependencies.* -3. **Add cleanup if needed.** Some Effects need to specify how to stop, undo, or clean up whatever they were doing. For example, "connect" needs "disconnect", "subscribe" needs "unsubscribe", and "fetch" needs either "cancel" or "ignore". You will learn how to do this by returning a *cleanup function*. +1. **声明 Effect**。默认情况下,Effect 会在每次渲染后都会执行。 +2. **指定 Effect 依赖**。大多数 Effect 应该按需执行,而不是在每次渲染后都执行。例如,淡入动画应该只在组件出现时触发。连接和断开服务器的操作只应在组件出现和消失时,或者切换聊天室时执行。文章将介绍如何通过指定依赖来控制如何按需执行。 +3. **必要时添加清理(cleanup)函数**。有时 Effect 需要指定如何停止、撤销,或者清除它的效果。例如,“连接”操作需要“断连”,“订阅”需要“退订”,“获取”既需要“取消”也需要“忽略”。你将学习如何使用 **清理函数** 来做到这一切。 -Let's look at each of these steps in detail. +以下是具体步骤。 -### Step 1: Declare an Effect {/*step-1-declare-an-effect*/} +### 第一步:声明 Effect {/*step-1-declare-an-effect*/} -To declare an Effect in your component, import the [`useEffect` Hook](/reference/react/useEffect) from React: +首先在 React 中引入 [`useEffect` Hook](/reference/react/useEffect): ```js import { useEffect } from 'react'; ``` -Then, call it at the top level of your component and put some code inside your Effect: +然后,在组件顶部调用它,并传入在每次渲染时都需要执行的代码: ```js {2-4} function MyComponent() { useEffect(() => { - // Code here will run after *every* render + // 每次渲染后都会执行此处的代码 }); return
; } ``` -Every time your component renders, React will update the screen *and then* run the code inside `useEffect`. In other words, **`useEffect` "delays" a piece of code from running until that render is reflected on the screen.** +每当你的组件渲染时,React 将更新屏幕,然后运行 `useEffect` 中的代码。换句话说,**`useEffect` 会把这段代码放到屏幕更新渲染之后执行**。 -Let's see how you can use an Effect to synchronize with an external system. Consider a `` React component. It would be nice to control whether it's playing or paused by passing an `isPlaying` prop to it: +让我们看看如何使用 Effect 与外部系统同步。考虑一个 `` React 组件。通过传递布尔类型的 `isPlaying` prop 以控制是播放还是暂停: ```js ; ``` -Your custom `VideoPlayer` component renders the built-in browser [`