翻译练习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’取消订阅,