如何使用useEffect React钩子

Check out my React hooks introduction first, if you’re new to them.

如果您是新手,请先查看我的React hooks简介

One React hook I sometimes use is useEffect.

我有时使用的一个React挂钩是useEffect

import React, { useEffect } from 'react'

One 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 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

翻译自: https://flaviocopes.com/react-hook-useeffect/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值