react钩子_React钩子简介

react钩子

Hooks is a feature that will be introduced in React 16.7, and is going to change how we write React apps in the future.

Hooks是一个将在React 16.7中引入的功能,它将在将来改变我们编写React应用程序的方式。

Before Hooks appeared, some key things in components were only possible using class components: having their own state, and using lifecycle events. Function components, lighter and more flexible, were limited in functionality.

在Hooks出现之前,组件中的某些关键事物只有使用类组件才能实现:拥有自己的状态以及使用生命周期事件。 功能组件更轻巧,更灵活,功能受到限制。

Hooks allow function components to have state and to respond to lifecycle events too, and kind of make class components obsolete. They also allow function components to have a good way to handle events.

挂钩允许函数组件具有状态并响应生命周期事件 ,并使类组件过时。 它们还允许功能组件具有处理事件的好方法。

访问状态 (Access state)

Using the useState() API, you can create a new state variable, and have a way to alter it. useState() accepts the initial value of the state item and returns an array containing the state variable, and the function you call to alter the state. Since it returns an array we use array destructuring to access each individual item, like this: const [count, setCount] = useState(0)

使用useState() API,您可以创建一个新的状态变量,并可以更改它。 useState()接受状态项的初始值,并返回一个包含状态变量的数组,以及一个用来更改状态的函数。 因为它返回一个数组,所以我们使用数组解构来访问每个单独的项,如下所示: const [count, setCount] = useState(0)

Here’s a practical example:

这是一个实际的例子:

import { useState } from 'react'

const Counter = () => {
  const [count, setCount] = useState(0)

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

ReactDOM.render(<Counter />, document.getElementById('app'))

You can add as many useState() calls you want, to create as many state variables as you want. Just make sure you call it in the top level of a component (not in an if or in any other block).

您可以添加useState()调用,以创建useState()状态变量。 只要确保在组件的顶层(而不是if或任何其他块中)调用它即可。

Example on Codepen:

Codepen上的示例:

See the Pen React Hooks example #1 counter by Flavio Copes (@flaviocopes) on CodePen.

见笔阵营鱼钩示例#1计数器由弗拉维奥COPES( @flaviocopes上) CodePen

访问生命周期挂钩 (Access lifecycle hooks)

Another very important feature of Hooks is allowing function components to have access to the lifecycle hooks.

挂钩的另一个非常重要的功能是允许功能组件访问生命周期挂钩。

Using class components you can register a function on the componentDidMount, componentWillUnmount and componentDidUpdate events, and those will serve many use cases, from variables initialization to API calls to cleanup.

使用类组件,您可以在componentDidMountcomponentWillUnmountcomponentDidUpdate事件上注册一个函数,这些事件将服务于许多用例,从变量初始化到API调用再到清理。

Hooks provide the useEffect() API. The call accepts a function as an argument.

挂钩提供useEffect() API。 该调用接受一个函数作为参数。

The function runs when the component is first rendered, and on every subsequent re-render/update. React first updates the DOM, then calls any function passed to useEffect(). All without blocking the UI rendering even on blocking code, unlike the old componentDidMount and componentDidUpdate, which makes our apps feel faster.

该函数在首次渲染组件时以及随后的每个重新渲染/更新时运行。 React首先更新DOM,然后调用传递给useEffect()任何函数。 与旧的componentDidMountcomponentDidUpdate不同,所有这些都不会阻止UI呈现,甚至在阻止代码时也不会阻止UI呈现,这使我们的应用程序感觉更快。

Example:

例:

const { useEffect, useState } = React

const CounterWithNameAndSideEffect = () => {
  const [count, setCount] = useState(0)
  const [name, setName] = useState('Flavio')

  useEffect(() => {
    console.log(`Hi ${name} you clicked ${count} times`)
  })

  return (
    <div>
      <p>
        Hi {name} you clicked {count} times
      </p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
      <button onClick={() => setName(name === 'Flavio' ? 'Roger' : 'Flavio')}>
        Change name
      </button>
    </div>
  )
}

ReactDOM.render(
  <CounterWithNameAndSideEffect />,
  document.getElementById('app')
)

The same componentWillUnmount job can be achieved by optionally returning a function from our useEffect() parameter:

可以通过有选择地从useEffect()参数返回一个函数来实现相同的componentWillUnmount作业:

useEffect(() => {
  console.log(`Hi ${name} you clicked ${count} times`)
  return () => {
    console.log(`Unmounted`)
  }
})

useEffect() can be called multiple times, which is nice to separate unrelated logic (something that plagues the class component lifecycle events).

useEffect()可以被多次调用,这很好地分离了不相关的逻辑(困扰类组件生命周期事件的东西)。

Since the useEffect() functions are run on every subsequent re-render/update, we can tell React to skip a run, for performance purposes, by adding a second parameter which is an array that contains a list of state variables to watch for. React will only re-run the side effect if one of the items in this array changes.

由于useEffect()函数是在随后的每个重新渲染/更新上运行的,因此,为了提高性能,我们可以告诉React跳过运行,方法是添加第二个参数,该参数是一个数组,其中包含要观察的状态变量列表。 如果此数组中的一项发生更改,React只会重新运行副作用。

useEffect(
  () => {
    console.log(`Hi ${name} you clicked ${count} times`)
  },
  [name, count]
)

Similarly, you can tell React to only execute the side effect once (at mount time), by passing an empty array:

同样,您可以通过传递一个空数组来告诉React仅执行一次副作用(在安装时):

useEffect(() => {
  console.log(`Component mounted`)
}, [])

useEffect() is great for adding logs, accessing 3rd party APIs and much more.

useEffect()非常适合添加日志,访问第三方API等。

Example on Codepen:

Codepen上的示例:

See the Pen React Hooks example #3 side effects by Flavio Copes (@flaviocopes) on CodePen.

见笔阵营鱼钩示例#3的副作用由弗拉维奥COPES( @flaviocopes上) CodePen

使用自定义钩子启用跨组件通信 (Enable cross-component communication using custom hooks)

The ability to write your own hooks is the feature that is going to significantly alter how you write React apps in the future.

能够编写自己的钩子的功能将在将来极大地改变您编写React应用程序的方式。

Using custom hooks you have one more way to share state and logic between components, adding a significant improvement to the patterns of render props and higher-order components. Which are still great, but now with custom hooks have less relevance in many use cases.

使用自定义钩子,您还有另一种在组件之间共享状态和逻辑的方法,从而大大改善了渲染道具和高阶组件的模式。 仍然很棒,但是现在在许多用例中,使用自定义钩子的相关性都较小。

How do you create a custom hook?

如何创建自定义钩子?

A hook is a function that conventionally starts with use. It can accept an arbitrary number of arguments, and return anything it wants.

钩子通常是从use开始的功能。 它可以接受任意数量的参数,并返回所需的任何内容。

Examples:

例子:

const useGetData() {
  //...
  return data
}

or

要么

const useGetUser(username) {
  //...const user = fetch(...)
  //...const userData = ...
  return [user, userData]
}

In your own components, you can use the hook like this:

在自己的组件中,可以使用如下所示的钩子:

const MyComponent = () => {
  const data = useGetData()
  const [user, userData] = useGetUser('flavio')
  //...
}

When exactly to add hooks instead of regular functions should be determined on a use case basis, and only experience will tell.

应根据用例确定何时确切添加钩子而不是常规功能,只有经验才能证明。

翻译自: https://flaviocopes.com/react-hooks/

react钩子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值