Skip to content

Commit

Permalink
hooks-intro
Browse files Browse the repository at this point in the history
  • Loading branch information
lixiaoyang1992 committed Feb 23, 2019
1 parent bcbe394 commit 11e833f
Showing 1 changed file with 46 additions and 44 deletions.
90 changes: 46 additions & 44 deletions content/docs/hooks-intro.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
---
id: hooks-intro
title: Introducing Hooks
title: Hooks简介
permalink: docs/hooks-intro.html
next: hooks-overview.html
---

*Hooks* are a new addition in React 16.8. They let you use state and other React features without writing a class.
*Hooks*是React 16.8中的增加的新特性。它使你在类之外使用state和其他React特性。

```js{4,5}
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
// 声明一个新的叫做“count”的state变量
const [count, setCount] = useState(0);
return (
Expand All @@ -25,86 +25,88 @@ function Example() {
}
```

This new function `useState` is the first "Hook" we'll learn about, but this example is just a teaser. Don't worry if it doesn't make sense yet!
这个叫做`useState`的新函数是我们学习的第一个“Hooks”,这个例子只是一个开场戏。如果你现在还一头雾水,不必担心。

**You can start learning Hooks [on the next page](/docs/hooks-overview.html).** On this page, we'll continue by explaining why we're adding Hooks to React and how they can help you write great applications.
**你可以在[下一页](/docs/hooks-overview.html)开始学习Hooks 。**在这一页,我们将继续解释我们为什么在React中加入Hooks,以及它将如何帮助你写出更好的应用。

>Note
>注意
>
>React 16.8.0 is the first release to support Hooks. When upgrading, don't forget to update all packages, including React DOM. React Native will support Hooks in the next stable release.
>React 16.8.0是第一个支持Hooks的版本。升级时请升级所有的package,包括React DOMReact Native将在下一个稳定版本中支持Hooks。
## Video Introduction {#video-introduction}
## 视频介绍 {#video-introduction}

At React Conf 2018, Sophie Alpert and Dan Abramov introduced Hooks, followed by Ryan Florence demonstrating how to refactor an application to use them. Watch the video here:
在React Conf 2018Sophie Alpert和Dan Abramov介绍了Hooks, 接下来Ryan Florence演示了如何使用它们重构一个应用. 你可以在这里看到这个视频:

<br>

<iframe width="650" height="366" src="//www.youtube.com/embed/dpw9EHDh2bM" frameborder="0" allowfullscreen></iframe>

## No Breaking Changes {#no-breaking-changes}
## 没有破坏性改动 {#no-breaking-changes}

Before we continue, note that Hooks are:
在我们继续之前,请记住Hooks是:

* **Completely opt-in.** You can try Hooks in a few components without rewriting any existing code. But you don't have to learn or use Hooks right now if you don't want to.
* **100% backwards-compatible.** Hooks don't contain any breaking changes.
* **Available now.** Hooks are now available with the release of v16.8.0.
* **完全可选的。** 你无需重写任何已有代码就可以在一些组件中尝试Hooks。但是如果你不想,你不必现在就去学习或使用Hooks。
* **100%向后兼容的。** Hooks不包含任何破坏性改动。
* **现在可用的。** Hooks在v16.8.0中已实装。

**There are no plans to remove classes from React.** You can read more about the gradual adoption strategy for Hooks in the [bottom section](#gradual-adoption-strategy) of this page.
**没有计划从React中移除类。** 你可以在本页[底部的章节](#gradual-adoption-strategy)读到更多关于Hooks的渐进策略。

**Hooks don't replace your knowledge of React concepts.** Instead, Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. As we will show later, Hooks also offer a new powerful way to combine them.
**Hooks不会影响你对React概念的理解。** 恰恰相反,Hooks提供更直接的API去使用你已知的React概念: props, state, context, refs和生命周期。我们将稍后展示,Hooks也提供了一种更强大的方式来组合他们。

**If you just want to start learning Hooks, feel free to [jump directly to the next page!](/docs/hooks-overview.html)** You can also keep reading this page to learn more about why we're adding Hooks, and how we're going to start using them without rewriting our applications.
**如果你只想开始学习Hooks,你可以[直接跳到下一页!](/docs/hooks-overview.html)** 你也可以继续阅读这一页来了解为什么我们要添加Hooks,以及我们将如何在不重写应用的情况下使用他们。

## Motivation {#motivation}
## 动机 {#motivation}

Hooks solve a wide variety of seemingly unconnected problems in React that we've encountered over five years of writing and maintaining tens of thousands of components. Whether you're learning React, use it daily, or even prefer a different library with a similar component model, you might recognize some of these problems.
Hooks解决了我们五年来编写和维护成千上万的组件时遇到的各种各样看起来不相关的问题。无论你正在学习React,或每天使用,或者更愿尝试另一个和React有相似组件模型的框架,你也许对这些问题似曾相识。

### It's hard to reuse stateful logic between components {#its-hard-to-reuse-stateful-logic-between-components}
### 在组件之间复用包含状态的逻辑很难 {#its-hard-to-reuse-stateful-logic-between-components}

React doesn't offer a way to "attach" reusable behavior to a component (for example, connecting it to a store). If you've worked with React for a while, you may be familiar with patterns like [render props](/docs/render-props.html) and [higher-order components](/docs/higher-order-components.html) that try to solve this. But these patterns require you to restructure your components when you use them, which can be cumbersome and make code harder to follow. If you look at a typical React application in React DevTools, you will likely find a "wrapper hell" of components surrounded by layers of providers, consumers, higher-order components, render props, and other abstractions. While we could [filter them out in DevTools](https://github.com/facebook/react-devtools/pull/503), this points to a deeper underlying problem: React needs a better primitive for sharing stateful logic.
React没有提供给一个组件“附上”可复用的行为的途径(例如,把组件连接到store)。如果你用过React一段时间,你也许会熟悉一些为了解决这个问题的而推出的模式,比如[render props](/docs/render-props.html)[高阶组件](/docs/higher-order-components.html) 。但是这些模式需要你重新组织你的组件结构,这可能会很笨重,使你的代码难以理解。如果你在React DevTools中观察一个典型的React应用,你会发现一个由providers, consumers, 高阶组件, render props等其他抽象层组成的嵌套地狱。我们可以[在DevTools过滤掉它们](https://github.com/facebook/react-devtools/pull/503),这指出了一个更深层次的问题:React需要更好的原函数以复用包含状态的逻辑。

With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. **Hooks allow you to reuse stateful logic without changing your component hierarchy.** This makes it easy to share Hooks among many components or with the community.
你可以使用Hooks从组件中提取包含状态的逻辑,使得这些逻辑可以单独测试并复用。**Hooks使你在无需修改组件结构的情况下复用包含状态的逻辑。**这使得在众多组件间或社区内分享Hooks很便捷。

We'll discuss this more in [Building Your Own Hooks](/docs/hooks-custom.html).
我们将在[自定义 Hooks](/docs/hooks-custom.html)展开更多讨论。

### Complex components become hard to understand {#complex-components-become-hard-to-understand}
### 复杂的组件变得难以理解 {#complex-components-become-hard-to-understand}

We've often had to maintain components that started out simple but grew into an unmanageable mess of stateful logic and side effects. Each lifecycle method often contains a mix of unrelated logic. For example, components might perform some data fetching in `componentDidMount` and `componentDidUpdate`. However, the same `componentDidMount` method might also contain some unrelated logic that sets up event listeners, with cleanup performed in `componentWillUnmount`. Mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs and inconsistencies.
我们经常维护一些组件,他们一开始很简单但是逐渐变得充满了状态逻辑和副作用。每一个生命周期常常包含一些不相关的逻辑。例如,组件常常在`componentDidMount``componentDidUpdate`中获取数据。但是,同一个`componentDidMount`中可能也包含一些其它的逻辑如设置事件监听,之后在`componentWillUnmount`中清除。强关联需要对照修改的代码被分离,而完全不相关的代码在一个方法中组合在了一起。很容易导致bug和不一致。

In many cases it's not possible to break these components into smaller ones because the stateful logic is all over the place. It's also difficult to test them. This is one of the reasons many people prefer to combine React with a separate state management library. However, that often introduces too much abstraction, requires you to jump between different files, and makes reusing components more difficult.
在很多情况下,由于包含状态的逻辑到处都是,所以不可能将这些组件拆分成更小的粒度。也很难测试它们。这是很多人将React和单独状态管理库结合使用的原因。但是,那常常引入了太多的抽象,使你在不同的文件之间来回切换,使得复用变得更加困难。

To solve this, **Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data)**, rather than forcing a split based on lifecycle methods. You may also opt into managing the component's local state with a reducer to make it more predictable.
为了解决这个问题,**Hooks使你将一个组件中相互关联的部分分离成更小的函数(比如设置一个订阅或获取数据)**,而不是强制按照生命周期划分。你还可以使用一个reducer来管理组件的本地状态,以使其更加可预测。

We'll discuss this more in [Using the Effect Hook](/docs/hooks-effect.html#tip-use-multiple-effects-to-separate-concerns).
我们将在[使用Effect Hook](/docs/hooks-effect.html#tip-use-multiple-effects-to-separate-concerns)展开更多讨论。

### Classes confuse both people and machines {#classes-confuse-both-people-and-machines}
### 人类和机器都对类感到困惑 {#classes-confuse-both-people-and-machines}

In addition to making code reuse and code organization more difficult, we've found that classes can be a large barrier to learning React. You have to understand how `this` works in JavaScript, which is very different from how it works in most languages. You have to remember to bind the event handlers. Without unstable [syntax proposals](https://babeljs.io/docs/en/babel-plugin-transform-class-properties/), the code is very verbose. People can understand props, state, and top-down data flow perfectly well but still struggle with classes. The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers.
除了使代码复用和管理更困难外,我们还发现类是学习React的一大屏障。你必须去理解JavaScript和其他语言差异巨大的`this`的工作方式。你不得不记得绑定事件处理器。没有稳定的[语法提案](https://babeljs.io/docs/en/babel-plugin-transform-class-properties/),这些代码非常啰嗦。人们可以很好地理解props, state和自顶向下的数据流,但又难以掌握类。即便在有经验的React开发者中,函数式和类式组件的差异和在什么情况下使用也会导致分歧。

Additionally, React has been out for about five years, and we want to make sure it stays relevant in the next five years. As [Svelte](https://svelte.technology/), [Angular](https://angular.io/), [Glimmer](https://glimmerjs.com/), and others show, [ahead-of-time compilation](https://en.wikipedia.org/wiki/Ahead-of-time_compilation) of components has a lot of future potential. Especially if it's not limited to templates. Recently, we've been experimenting with [component folding](https://github.com/facebook/react/issues/7323) using [Prepack](https://prepack.io/), and we've seen promising early results. However, we found that class components can encourage unintentional patterns that make these optimizations fall back to a slower path. Classes present issues for today's tools, too. For example, classes don't minify very well, and they make hot reloading flaky and unreliable. We want to present an API that makes it more likely for code to stay on the optimizable path.
另外,React已经发布五年了,我们希望它能在下一个五年保持相关。就像[Svelte](https://svelte.technology/), [Angular](https://angular.io/), [Glimmer](https://glimmerjs.com/)和其它的库展示的那样,组件的[预先编译](https://en.wikipedia.org/wiki/Ahead-of-time_compilation)有巨大的潜力。尤其是在它不局限于模板的时候。最近,我们一直在使用[Prepack](https://prepack.io/)来试验[component folding](https://github.com/facebook/react/issues/7323),并且我们看到了有希望的早期结果。但是我们发现类组件可能会导致一些让这些优化措施无效的模式。类也给今天的工具带来了一些issue。例如,类不能很好的压缩,并且使热重载很古怪且不可靠。我们想要提供一个使代码便于优化的API。

To solve these problems, **Hooks let you use more of React's features without classes.** Conceptually, React components have always been closer to functions. Hooks embrace functions, but without sacrificing the practical spirit of React. Hooks provide access to imperative escape hatches and don't require you to learn complex functional or reactive programming techniques.
为了解决这些问题,**Hooks使你在类之外使用更多的React特性。**从概念上讲,React组件一直更近似于函数。Hooks拥抱了函数,但是避免了牺牲React的实践精神。Hooks提供了问题的解决方案,无需学习复杂的函数式或响应式编程技术。

>Examples
>示例
>
>[Hooks at a Glance](/docs/hooks-overview.html) is a good place to start learning Hooks.
>[Hooks概述](/docs/hooks-overview.html)开始学习会是不错的开始。
## Gradual Adoption Strategy {#gradual-adoption-strategy}
## 渐进策略 {#gradual-adoption-strategy}

>**TLDR: There are no plans to remove classes from React.**
>**太长不看: 没有计划从React中移除类。**
We know that React developers are focused on shipping products and don't have time to look into every new API that's being released. Hooks are very new, and it might be better to wait for more examples and tutorials before considering learning or adopting them.
我们知道React开发者们专注于开发产品,没有时间关注每一个新发布的API。Hooks很新,也许等到有更多的例子和教程后考虑学习或采用它们会更好。

We also understand that the bar for adding a new primitive to React is extremely high. For curious readers, we have prepared a [detailed RFC](https://github.com/reactjs/rfcs/pull/68) that dives into motivation with more details, and provides extra perspective on the specific design decisions and related prior art.
我们也明白向React添加新原函数的标准非常高。我们为好奇的读者准备了[详细的征求意见文档](https://github.com/reactjs/rfcs/pull/68),在文档中提供了更多细节,有关具体设计决策的额外视角以及现有的相关技术。

**Crucially, Hooks work side-by-side with existing code so you can adopt them gradually.** There is no rush to migrate to Hooks. We recommend avoiding any "big rewrites", especially for existing, complex class components. It takes a bit of a mindshift to start "thinking in Hooks". In our experience, it's best to practice using Hooks in new and non-critical components first, and ensure that everybody on your team feels comfortable with them. After you give Hooks a try, please feel free to [send us feedback](https://github.com/facebook/react/issues/new), positive or negative.
**最重要的是,Hooks和现有代码可以同时工作,你可以逐渐的采用他们。**我们分享这个试验性的API以便得到对打造React的未来感兴趣的人们的早期反馈——我们将在开放的基础上开发Hooks。

We intend for Hooks to cover all existing use cases for classes, but **we will keep supporting class components for the foreseeable future.** At Facebook, we have tens of thousands of components written as classes, and we have absolutely no plans to rewrite them. Instead, we are starting to use Hooks in the new code side by side with classes.
最后,不用急于迁移到Hooks。我们建议避免任何“大规模重写”,尤其使对于现有的复杂的类组件。需要一些思维转变来开始“thinking in Hooks”。依我们的经验,最好从新的非关键的组件开始练习使用Hooks,并且确保你的团队中的每一员对Hooks感到舒服。在你尝试过Hooks之后,欢迎[给我们反馈](https://github.com/facebook/react/issues/new)任何意见。

## Frequently Asked Questions {#frequently-asked-questions}
我们准备让Hooks覆盖所有为类准备的用例,但是**我们将继续为类组件提供支持。**在Facebook,我们有成千上万的组件用类书写,我们完全没有重写它们的计划。相反,我们开始在新的代码中同时使用Hooks和类。

We've prepared a [Hooks FAQ page](/docs/hooks-faq.html) that answers the most common questions about Hooks.
## 常见问题 {#frequently-asked-questions}

## Next Steps {#next-steps}
我们准备了一个[Hooks常见问题](/docs/hooks-faq.html)来解答最常见的关于Hooks的问题。

By the end of this page, you should have a rough idea of what problems Hooks are solving, but many details are probably unclear. Don't worry! **Let's now go to [the next page](/docs/hooks-overview.html) where we start learning about Hooks by example.**
## 下一步 {#next-steps}

在这一页的最后,你应该对Hooks能解决什么问题有了粗略的理解,但可能还有许多细节不清楚。不要担心!**让我们去[下一页](/docs/hooks-overview.html)通过例子学习Hooks。**

0 comments on commit 11e833f

Please # to comment.