Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React Hooks.2 - Hooks at a Glance(Hooks 一览) #101

Open
tcatche opened this issue Apr 3, 2019 · 0 comments
Open

React Hooks.2 - Hooks at a Glance(Hooks 一览) #101

tcatche opened this issue Apr 3, 2019 · 0 comments

Comments

@tcatche
Copy link
Owner

tcatche commented Apr 3, 2019

本文博客地址:React Hooks.2 - Hooks at a Glance(Hooks 一览).

Hooks are a new feature proposal that lets you use state and other React features without writing a class. They're currently in React v16.7.0-alpha and being discussed in an open RFC.

Hooks 是一项新提案,可让你在不编写类的情况下使用 state 和其他React 功能。 它们目前在 React v16.7.0-alpha 中可用,并在open RFC 中讨论。

Hooks are backwards-compatible. This page provides an overview of Hooks for experienced React users.

Hooks 是向后兼容的。本文为经验丰富的 React 用户提供了 Hooks 的概述。

This is a fast-paced overview. If you get confused, look for a yellow box like this:

这是一个快速了解的概述。如果你感到困惑,请找这样的概括:

Detailed Explanation
详细解释
Read the Motivation to learn why we're introducing Hooks to React.
阅读动机 以了解我们为何将 Hooks 引入React。

↑↑↑ Each section ends with a yellow box like this. They link to detailed explanations.

↑↑↑ 每一节的结尾都以这样的黄色背景结束(译者的主题并没有设置黄色 2333) 它们链接到到详细的解释。

📌 State Hook

This example renders a counter. When you click the button, it increments the value:

这个示例渲染了一个计数器。当你点击按钮时,它会将值递增1:

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Here, useState is a Hook (we'll talk about what this means in a moment). We call it inside a function component to add some local state to it. React will preserve this state between re-renders. useState returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It's similar to this.setState in a class, except it doesn't merge the old and new state together. (We'll show an example comparing useState to this.state in Using the State Hook.)

这里的 useState 就是一个 Hook(我们将在稍后讨论这是什么意思)。我们在函数组件中调用它来向它添加一些内部状态。React 将在多次渲染之间保留此状态。useState 返回一对内容:当前状态值和允许你更新这个状态值的函数。你可以从事件处理程序或其他位置调用此函数。它类似于类中的this.setState,除了它不会将旧状态和新状态合并在一起。
(我们将在使用State Hook 演示 useStatethis.state 比较的示例。)

The only argument to useState is the initial state. In the example above, it is 0 because our counter starts from zero. Note that unlike this.state, the state here doesn't have to be an object -- although it can be if you want. The initial state argument is only used during the first render.

useState 的唯一参数是初始状态。在上面的例子中,它是 0 ,因为我们的计数器从零开始。
请注意,与 this.state 不同,此处的状态不必是对象 - 可以是任意你想要的类型。
初始状态参数仅在第一次渲染时使用。

Declaring multiple state variables(声明多个状态变量)

You can use the State Hook more than once in a single component:

你可以在一个组件中多次使用 State Hook:

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}

The array destructuring syntax lets us give different names to the state variables we declared by calling useState. These names aren't a part of the useState API. Instead, React assumes that if you call useState many times, you do it in the same order during every render. We'll come back to why this works and when this is useful later.

数组解构 语法允许我们为通过调用 useState 声明的状态变量赋予不同的名称。这些名称不是useState API的一部分。相反,React 假定如果多次调用 useState,则在每次渲染期间以相同的顺序执行。稍后,我们将解释为什么可以这样以及何时有用。

But what is a Hook?

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don't work inside classes -- they let you use React without classes. (We don't recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you'd like.)

Hooks 是允许你从函数组件 “Hooks” 到 React 状态和生命周期的功能。
钩子在类里不起作用--它们允许你在没有类的情况下使用 React。(我们不建议你立即重写现有组件,但如果你愿意,可以开始在新组件中使用Hook。)

React provides a few built-in Hooks like useState. You can also create your own Hooks to reuse stateful behavior between different components. We'll look at the built-in Hooks first.

React 提供了一些像 useState 这样的内置 Hooks。你还可以创建自己的 Hooks 以在不同组件间重用状态行为。我们先来看看内置的 Hooks。

Detailed Explanation
详细说明
You can learn more about the State Hook on a dedicated page: Using the State Hook.
你可以在此专题页面上了解更多有关 State Hook的更多信息:使用 State Hook

⚡️ Effect Hook

You've likely performed data fetching, subscriptions, or manually changing the DOM from React components before. We call these operations "side effects" (or "effects" for short) because they can affect other components and can't be done during rendering.

你之前可能从 React 组件执行数据获取,订阅内容或手动更改 DOM。我们将这些操作称为“包含副作用的操作”(或简称为“副作用”),因为它们会影响其他组件,并且在渲染过程中无法完成。

The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API. (We'll show examples comparing useEffect to these methods in Using the Effect Hook.)

操作副作用的 Hook,useEffect 增加了从函数组件执行“副作用”的功能。它与 React 类中的componentDidMountcomponentDidUpdatecomponentWillUnmount 具有相同的用途,但统一为单个API。(我们将在使用副作用 Hook 中比较 useEffect 与这些方法差异的示例。)

For example, this component sets the document title after React updates the DOM:

例如,下面这个组件在 React 更新到 DOM 后设置文档标题:

import { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

When you call useEffect, you're telling React to run your "effect" function after flushing changes to the DOM. Effects are declared inside the component so they have access to its props and state. By default, React runs the effects after every render -- including the first render. (We'll talk more about how this compares to class lifecycles in Using the Effect Hook.)

当你调用 useEffect 时,你告诉 React 在刷新对 DOM 的更改后运行你的 effect 函数。effect 在组件内声明,因此可以访问其 props 和 state 。默认情况下,React 在每次渲染后运 行effect --包括第一次渲染。(我们将在使用 Effect Hook 中更多地讨论它与类生命周期的比较。)

Effects may also optionally specify how to "clean up" after them by returning a function. For example, this component uses an effect to subscribe to a friend's online status, and cleans up by unsubscribing from it:

effect 还可以通过返回函数指定如何“清理”它们。例如,下面这个组件使用 effect 来订阅朋友的在线状态,并通过取消订阅来清理:

import { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }

  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);

    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

In this example, React would unsubscribe from our ChatAPI when the component unmounts, as well as before re-running the effect due to a subsequent render. (If you want, there's a way to tell React to skip re-subscribing if the props.friend.id we passed to ChatAPI didn’t change.)

在此示例中,当组件卸载时,以及在由于后续渲染而重新运行效果之前,React将 取消订阅我们的ChatAPI。
(如果你愿意的话,如果我们传递给 ChatAPI 的 props.friend.id 没有改变,有办法告诉 React 跳过重新订阅。)

Just like with useState, you can use more than a single effect in a component:

就像使用 useState 一样,你可以在组件中使用多个 effect:

function FriendStatusWithCounter(props) {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  const [isOnline, setIsOnline] = useState(null);
  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }
  // ...

Hooks let you organize side effects in a component by what pieces are related (such as adding and removing a subscription), rather than forcing a split based on lifecycle methods.

Hooks 允许您自由组织组件中相关联的副作用(例如添加和删除订阅)在一起,而不是被不同的生命周期方法强制拆分到不同的方法中。

Detailed Explanation
详细解释
You can learn more about useEffect on a dedicated page: Using the Effect Hook.
你可以在此页面上了解关于 useEffect 的更多信息:使用 Effect Hook

✌️ Rules of Hooks

Hooks are JavaScript functions, but they impose two additional rules:

Hooks 是 JavaScript 函数,但它强加了两个额外的规则:

  • Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
  • 只能在顶层调用 Hooks。不要在循环,条件或嵌套函数中调用 Hook。
  • Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions. (There is just one other valid place to call Hooks -- your own custom Hooks. We'll learn about them in a moment.)
  • 仅在 React 函数组件中调用 Hooks。不要从常规 JavaScript 函数中调用 Hook。(还有另一个被允许的地方调用 Hooks -- 你的自定义 Hooks。我们马上就会介绍它们。)

We provide a linter plugin to enforce these rules automatically. We understand these rules might seem limiting or confusing at first, but they are essential to making Hooks work well.

我们提供了一个linter 插件 来自动强制执行这些规则。我们知道这些规则最初可能看起来很受限制或令人困惑,但它们对于使 Hooks 良好运行至关重要。

Detailed Explanation
详细解释
You can learn more about these rules on a dedicated page: Rules of Hooks.
你可以在此页面上了解关于 Hooks 使用规则的更多信息:Hooks 使用规则

💡 Building Your Own Hooks

Sometimes, we want to reuse some stateful logic between components. Traditionally, there were two popular solutions to this problem: higher-order components and render props. Custom Hooks let you do this, but without adding more components to your tree.

有时,我们希望在组件之间重用一些状态的逻辑。传统上,这个问题有两个流行的解决方案:高阶组件render props。自定义 Hooks 允许您执行此操作,并且无需向树中添加更多组件。

Earlier on this page, we introduced a FriendStatus component that calls the useState and useEffect Hooks to subscribe to a friend's online status. Let's say we also want to reuse this subscription logic in another component.

在本页前面,我们介绍了一个调用 useState 和 useEffect Hooks 的 FriendStatus 组件来订阅朋友的在线状态。假设我们还希望在另一个组件中重用此订阅逻辑。

First, we'll extract this logic into a custom Hook called useFriendStatus:

首先,我们将这个逻辑提取到一个名为 useFriendStatus 的自定义 Hook 中:

import { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }

  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  });

  return isOnline;
}

It takes friendID as an argument, and returns whether our friend is online.

它将 friendID 作为参数,并返回我们的朋友是否在线。

Now we can use it from both components:

现在我们可以从两个组件中使用它:

function FriendStatus(props) {
  const isOnline = useFriendStatus(props.friend.id);

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}
function FriendListItem(props) {
  const isOnline = useFriendStatus(props.friend.id);

  return (
    <li style={{ color: isOnline ? 'green' : 'black' }}>
      {props.friend.name}
    </li>
  );
}

The state of these components is completely independent. Hooks are a way to reuse stateful logic, not state itself. In fact, each call to a Hook has a completely isolated state -- so you can even use the same custom Hook twice in one component.

这些组件的状态是完全独立的。Hooks 是重用已有状态逻辑的一种方式,而不是状态的本身。
事实上,每次调用 Hook 都有一个完全隔离的状态--所以你甚至可以在一个组件中使用相同的自定义Hook 两次。

Custom Hooks are more of a convention than a feature. If a function's name starts with "use" and it calls other Hooks, we say it is a custom Hook. The useSomething naming convention is how our linter plugin is able to find bugs in the code using Hooks.

自定义挂钩更像是一种约定而非功能。如果函数的名称以“use”开头并且它调用了其他 Hook,我们说它是一个自定义 Hook。useSomething 的命名约定使我们的 linter 插件能够在使用 Hooks 的代码中查找错误。

You can write custom Hooks that cover a wide range of use cases like form handling, animation, declarative subscriptions, timers, and probably many more we haven't considered. We are excited to see what custom Hooks the React community will come up with.

您可以编写自定义Hook,涵盖更广泛的使用场景,如表单处理,动画,声明订阅,计时器,以及可能还有更多我们没有考虑过的。我们很期望看到 React 社区发布各种定制的 Hooks。

Detailed Explanation
详细说明
You can learn more about custom Hooks on a dedicated page: Building Your Own Hooks.
你可以在此专题页面上关于自定义 Hook 的更多信息:创造你自己的 Hooks

🔌 Other Hooks

There are a few less commonly used built-in Hooks that you might find useful. For example, useContext lets you subscribe to React context without introducing nesting:

你可能会发现一些不太常用的内置 Hooks 也很有用。例如, useContext 允许你不引入嵌套来订阅 React context:

function Example() {
  const locale = useContext(LocaleContext);
  const theme = useContext(ThemeContext);
  // ...
}

And useReducer lets you manage local state of complex components with a reducer:

useReducer 允许你使用 reducer 管理复杂组件的内部状态:

function Todos() {
  const [todos, dispatch] = useReducer(todosReducer);
  // ...

Detailed Explanation
详细说明
You can learn more about all the built-in Hooks on a dedicated page: Hooks API Reference.
你可以在此页面上了解关于内置 Hooks 的更多信息:Hooks API 参考

Next Steps

Phew, that was fast! If some things didn't quite make sense or you'd like to learn more in detail, you can read the next pages, starting with the State Hook documentation.

如果这些介绍对你来说太简单了,或者你想详细了解更多内容,可以阅读下一节,从 State Hook 的文档开始。

You can also check out the Hooks API reference and the Hooks FAQ.

你还可以查看 Hooks API 参考Hooks常见问题解答

Finally, don't miss the introduction page which explains why we're adding Hooks and how we'll start using them side by side with classes -- without rewriting our apps.

最后,不要错过介绍页,它解释了我们为什么要添加 Hooks 以及我们将如何开始将它们与类搭配使用--而无需重写我们的应用程序。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant