翻译练习react-hooks -2 (16.8.4)

Hooks at a Glancs(Hooks概览)

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
Hooks 是 react16.8版本新增的功能.它能让你在没有用class的前提下使用state和一些其他React的特性

Hooks are backwards-compatible. This page provides an overview of Hooks for experienced React users. This is a fast-paced overview. If you get confused, look for a yellow box like this:
Hooks是向后兼容的,这一页提供一些关于Hooks的概览给有经验的React用户.这是一个快速浏览.如果你感到疑惑,可以查看类似这样黄色的框框.

Detailed Explanation
Read the Motivation to learn why we’re introducing Hooks to React.

详情解释
阅读React的动机了解一下为什么我们要为react引进Hooks

↑↑↑ Each section ends with a yellow box like this. They link to detailed explanations.
每个部分的结尾都有一个类似这样的黄色框框,这里面有详细解释的链接

State Hook

This example renders a counter. When you click the button, it increments the value:
这个例子渲染了一个计算器,当你点击按钮,数字就会加1

import React, { 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(我们待会再讨论这个是什么意思),我们能够在函数组件中通过调用它去添加一些内部的state.react将在在再次渲染前保存这个state.useState将会返回一对值,当前的state和一个了你更新它的函数.你能够把这个函数放在一个事件处理或者是一些其他地方调用.这类似于在class组件里面调用this.setState,除了它不能将旧的和新的state合并(我们将在一个使用state Hooks的例子里展示useState和this.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只有一个参数就是初始化state的值,在上面的例子,这个参数是0.因为我们的计算器是从0开始的.注意他不像this.state,这里的state不一定要是一个对象- 尽管你也可以这样去做.这个初始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我们声明一些state变量,我们可以使用数组的结构赋值语法赋予不同的名字.这些名字不是useState api的一部分,相反,当你多次调用useState时,react假设你在每次渲染都以相同的顺序调用他们,我们以后再来讨论为什么这样和以及什么时候会这样.

But what is a Hook?(但是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是让你能在函数组件里面挂钩React state和生命周期特性的函数,Hooks不在classes里面工作,为了让你使用React不需要classes.(我们不推荐重构你已存在的组件,但是如果你想尝试一下,可以在一些新的组件里面使用Hooks)

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提供一些内置的Hooks例如useState.你也可以创建属于你自己的Hooks在不同的组件间去复用充斥着状态的行为.我们先来看看内置的Hooks.

Detailed Explanation
You can learn more about the State Hook on a dedicated page: Using the State Hook.

详情解释
你可以在Using the State Hook.详情页面了解更多关于State Hook

Effect Hook(副作用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",添加到可能会执行副作用的函数组件.它的目的和componentDidMount, componentDidUpdate, and componentWillUnmount in React class中一样.但是统一成一个API(我们将会展示一些例子体现Using the Effect Hook使用'useEffect'和上述方法的区别)

For example, this component sets the document title after React updates the DOM:
例如,这个组件在React更新DOM节点后设置页面标题

import React, { 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之后运行你的"副作用"函数.这个函数是被声明在组件内的,所以它能够拿到组件的props和state.默认情况下,React会在每次渲染后运行副作用函数---包括第一次渲染(我们将在 Using the Effect Hook讨论更多关于组件生命周期和Effects的区别)

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:
副作用也可以在通过回调函数后面选择性的指定怎么去清空。举个例子,这个组件使用了一个监听朋友在线状态的副作用,同时也可以通过取消订阅去清空它
···
import React, { 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’取消订阅,

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,267评论 0 10
  • 今天下午儿子放学回家吃了饭,就写作业,我和他一起画了图形,画完就去洗脚睡觉了儿子。
    津恺阅读 146评论 0 0
  • “不要惧怕计划的庞大身躯,也不要低估聚沙为佛塔的力量。”
    丢你一颗榴莲阅读 117评论 0 0
  • Typora For Markdown 语法 数学表达式 要启用这个功能,首先到Preference->Edito...
    zCoding阅读 311评论 0 0
  • 《时间的镜中》文/阿剑 1 城市回到草木天空洗净脸庞 行走重新缓慢众人交谈与观望,都很安静 她微笑从大地之上跳回她...
    阿剑啊阅读 292评论 2 3