您的位置:首页 > Web前端 > React

react钩子_React钩101

2020-08-17 22:28 323 查看

react钩子

A quick reference to commonly used hooks

常用钩子的快速参考

I had a fun coding challenge recently where I had to build out a feature with React. It was definitely a nice change from a typical algorithmic coding challenge. The deliverable stated that I could only use functional components. But wait! I thought functional components couldn’t hold state. Incoming React hooks!

最近我遇到了一个有趣的编码挑战,当时我不得不使用React构建功能。 与典型的算法编码挑战相比,这绝对是一个不错的变化。 可交付成果指出,我只能使用功能组件。 可是等等! 我以为功能组件无法保持状态。 传入的React钩子!

什么是挂钩? (What are Hooks?)

React hooks were introduced in 2018 as a way to give functional components, well, more functionality with state. Traditionally, state is stored and managed in class components. Code held in class components can get long and convoluted considering all of the lifecycle methods and state you might have to write. The hooks system allows us to write more reusable code rather than the inheritance nature of class components. But just remember “Hooks don’t replace your knowledge of React concepts”. They build on top of concepts like props, state, context, refs, and lifecycle.

React钩子于2018年引入,是一种为功能组件提供状态的更多功能的方法。 传统上,状态是在类组件中存储和管理的。 考虑到所有生命周期方法和您可能必须编写的状态,保存在类组件中的代码可能会变得冗长而复杂。 钩子系统允许我们编写更多可重用的代码,而不是类组件的继承性质。 但是请记住“ 钩子不能代替您对React概念的了解” 。 它们建立在诸如道具状态上下文引用生命周期之类的概念之上。

设定档 (Config)

React hooks are a native feature of

create-react-app
. To use hooks, all you have to do is import React and destructure the hooks you want to use as shown in the gist below.

React挂钩是

create-react-app
的本机功能。 要使用钩子,您需要做的就是导入React并解构您要使用的钩子,如下所示。

常用挂钩 (Commonly Used Hooks)

There are ten native hooks available for use. They include:

useState
,
useEffect
,
useContext
,
useReducer
,
useCallback
,
useMemo
,
useRef
,
useImperativeHandle
,
useLayoutEffect
, and
useDebugValue
. There’s also an option to write custom hooks. For custom hooks, we can abstract hooks into a function that starts with the convention “
use____
”. I will talk about two common hooks below.

有十个本机钩子可供使用。 它们包括:

useState
useEffect
useContext
useReducer
useCallback
useMemo
useRef
useImperativeHandle
useLayoutEffect
useDebugValue
。 还有一个编写自定义钩子的选项。 对于自定义钩子,我们可以将钩子抽象到以约定“
use____
”开头的函数中。 我将在下面谈论两个常见的问题。

Some basic rules to know when using hooks are to:

使用钩子时要了解的一些基本规则是:

  1. Don’t use hooks inside vanilla JavaScript functions.

    不要在普通JavaScript函数中使用钩子。
  2. Use hooks at the top-level — meaning, don’t use them in loops, conditions, or nested functions. This is because is it possible to use many hooks in one component and the order of them matters. So we want to be able to preserve state correctly.

    在顶层使用钩子-表示不要在循环,条件或嵌套函数中使用它们。 这是因为可以在一个组件中使用多个挂钩,并且它们的顺序很重要。 因此,我们希望能够正确保留状态。

useState()—初始化,引用或更新状态 (useState() — initialize, reference, or update state)

useState
is the function that lets you use and manipulate state in a functional component. It uses array destructuring to allow for use two functions to reference a piece of state and to update state. The initial value of state is passed in as an argument of
useState
. A common use case would be to use the second element, the setter function, as a callback of an event handler. That setter function would be the equivalent of
setState
in a class component.

useState
是使您可以使用和操纵功能组件中的状态的函数。 它使用数组解构来允许使用两个函数来引用一个状态并更新状态。 state的初始值作为
useState
的参数
useState
。 一个常见的用例是将第二个元素(setter函数)用作事件处理程序的回调。 该setter函数将与类组件中的
setState
等效。

In the gist below, we can compare how state would be handled in a functional and class component. One benefit of

useState
is that only one line of code is necessary to do what lines 5 to 7 is doing.

在下面的要点中,我们可以比较如何在功能和类组件中处理状态。

useState
一个好处是,只需一行代码即可执行第5至7行。

useEffect()—与生命周期方法类似,例如componentDidMount()或componentDidUpdate() (useEffect() — similar to lifecycle methods like componentDidMount() or componentDidUpdate())

The next hook we’ll explore is called useEffect which is useful for actions to take when rendering and/or re-rendering. One common use case is to make requests and fetch data with

useEffect
. The use of
componentDidMount
is not possible in functional components. There are three scenarios to consider when using
useEffect
. This hook can run code automatically when the component:

我们将探讨的下一个钩子称为useEffect,它对于在渲染和/或重新渲染时采取的操作很有用。 一种常见的用例是使用

useEffect
发出请求并获取数据。 采用
componentDidMount
不可能的功能组件。 使用
useEffect
时需要考虑三种情况。 当组件出现以下情况时,此挂钩可以自动运行代码:

  1. Initially renders

    最初渲染
  2. Initially renders and also whenever it re-renders

    最初渲染以及每当重新渲染时
  3. Initially renders, whenever it re-renders as well as when data is changed

    最初渲染,无论何时重新渲染以及何时更改数据

Another way to think about those three scenarios is if you want to use

useEffect
with or without cleanup — meaning, do you want to express any side effects like running additional code after the initial render? If you decide to use
useEffect
to handle some cleanup, you can return a callback function to be invoked on the next render. One example use case would be to return cleanup function in order to cancel the timer on
setTimeout
. On the first render, the
setTimeout
function would run as normal, then on the second render, it will get canceled. Pretty neat stuff!

考虑这三种情况的另一种方法是,如果要使用

useEffect
进行清理,也可以不进行清理,这意味着要表达任何副作用,例如在初始渲染后运行其他代码吗? 如果决定使用
useEffect
进行一些清理,则可以返回要在下一次渲染时调用的回调函数 。 一种示例用例是返回清除函数,以取消
setTimeout
上的计时器。 在第一个渲染上,
setTimeout
函数将正常运行,然后在第二个渲染上,它将被取消。 漂亮的东西!

useEffect
can take a second argument of three things: nothing, an empty array, and an array with elements. It’s more than likely that you’ll either use a second arg of an array — filled or not. The second argument will run at the initial render. If there is filled array as a second arg,
useEffect
will run again if the data has since been changed.

useEffect
可以接受第二个参数,该参数包含以下三项内容:无,空数组和包含元素的数组。 您很有可能会使用数组的第二个arg-是否填充。 第二个参数将在初始渲染时运行。 如果将填充数组作为第二个arg,则
useEffect
数据已更改,
useEffect
将再次运行。

In the gist below, state is initially set to an empty array on line 3 with

setState
. On line 5, we use
useEffect
to fetch natively by adding an
async/await
function. You can of course use other libraries like axios to handle fetching. One thing to note is that the
useEffect
function itself cannot be
async
, which is why, below, the
async
keyword is used in
data()
instead. As a second argument, we pass in the array with the
results
which holds the data/state we’ve fetched and set with
setResults()
.

在下面的要点中,状态最初使用

setState
设置为第3行的空数组。 在第5行,我们使用
useEffect
通过添加
async/await
函数来本地获取。 您当然可以使用axios之类的其他库来处理获取。 要注意的一件事是
useEffect
函数本身不能是
async
,这就是为什么在下面的
data()
使用
async
关键字的原因 代替。 作为第二个参数,我们传递带有
results
的数组,该
results
保存我们已获取的数据/状态,并使用
setResults()
设置。

One of the cool things functional components can do is hold multiple

useState
and
useEffect
functions. Depending on those three scenarios listed above, you can use as many hooks as needed.

功能组件可以做的很酷的事情之一就是拥有多个

useState
useEffect
函数。 根据上面列出的三种情况,您可以根据需要使用任意数量的挂钩。

Hooks are a more modern way to write React and offer so much more functionality to functional components. They are definitely worth learning and can really transform and optimize your React apps.

挂钩是一种更现代的方式来编写React,并为功能组件提供了更多功能。 他们绝对值得学习,并且可以真正改变和优化您的React应用程序。

资源资源 (Resources)

翻译自: https://medium.com/weekly-webtips/react-hooks-101-83dc72a4cb69

react钩子

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: