til
  • README
  • Software Development Roles
  • solid
  • README
    • service-worker
  • docker
    • arg
    • 更新docker版本
  • editor
    • vscode
    • Creating a VS Code Theme
  • english
    • words
  • front-end
    • ==
    • ECMAScript
    • IIFE
    • Label
    • basic
    • html.js.css渲染顺序
    • npm-vs-yarn
    • obj-delete-key-value
    • react
    • split-join-and-replace
    • video
    • 前端自检清单
    • 递归及去重
    • css
      • css换肤
      • flex
      • list
      • nth-child和nth-of-type区别
      • padding
      • position
      • 层叠上下文
      • 层叠样式(+)
      • 正方形
      • 语义化标签
    • dom
      • DOCTYPE
      • HEAD
      • 修改document
      • 自定义表单验证
    • electron
      • basic
    • es6
      • basic-type
      • basic
      • prototype-example
      • defineProperty
      • understanding-es6
        • 0.introduction
        • Appendix A: Smaller Changes
        • Appendix B: Understanding ES7
        • Block-Binding
        • Proxies&Reflection
        • class
        • 解构赋值
        • function
        • improved-array
        • iterators&generators
        • modules
        • object
        • promise
        • Map&Set
        • symbol
    • images
      • 前端角度看图片
    • interview_case
      • lexical_scope
      • redux和localstroage存储位置
    • javascript
      • fuck-the-js
      • js-engine-work
      • js原生操作dom
      • what-is-function-program
      • 执行上下文
      • articles
        • JavaScript中使用函数组合
        • JavaScript中的依赖注入
        • JavaScript作用域链中的标识符解析和闭包
        • JavaScript是何如工作的--概述
        • JavaScript深拷贝
        • JavaScript的全局变量是如何工作的
        • js继承常见的误解
        • node12&chrome中7个新的提案功能
        • 你真的懂JavaScript吗
      • date
        • index
      • engines
        • basic
        • JavaScript引擎基础:外形和内联缓存
        • v8中推测性优化的介绍
        • 优化原型
        • 更快的异步功能和promise
      • events
        • baisc
        • 事件冒泡和捕获
        • 定义事件
        • 页面生命周期
      • higher-order-function
        • curry
        • monad
      • module
        • basic
        • main&module
      • objects
        • iterator
        • spread
        • examples
          • iterator
      • performance
        • blocking-css
        • cache
      • prototype
        • Property-Descriptors
        • basic
        • prototype-shadow
      • you-dont-known-js
        • async&performance
          • Chapter 1: Asynchrony: Now & Later
          • Chapter 2: Callbacks
          • Chapter 3: Promises
          • Chapter 4: Generators
        • scope & closures
          • apA
          • apB
          • apC
          • apD
          • chapter1-what-is-scope
          • chapter2-lexical-scope
          • chapter3-function-vs-block-scope
          • chapter4-hoisting
          • chapter5-scope-closure
        • this & object prototypes
          • chapter1-this-or-that
          • chapter2-this-make-sense
          • chapter3-objects
          • chapter4-mixing(up)-class-object
          • chapter5-prototype
          • chapter6-behavior-delegation
        • types&grammer
          • Chapter1-Types
          • Chapter2-Values
          • Chapter3-Natives
          • Chapter4-coercion
          • Chapter5-grammer
        • up & going
          • chapter1-into-programming
          • chapter2-into-javascript
          • chapter3-into-YDKJS
    • mobile
      • iPhone分辨率终极指南
    • npm
      • arguments
      • build
    • react-native
      • prop-methods
    • react
      • PropTypes
      • basic
      • codebase-overview
      • component-element-instance
      • context
      • how-to-known-component-is-func-or-class
      • overview
      • react16.9
      • react18计划
      • react的设计原则
      • reconciliation
      • setState
      • useMemo
      • why-do-we-write-super-props
      • 从头实现一个react
      • concurrent
        • 引入并发模式(仅试验)
      • conf
        • conf-2019
      • events
        • 合成事件概述
      • hooks
        • custom-hook
        • effect-hook
        • hooks-api
        • intro
        • overview
        • rules
        • state-hook
        • hooks-vs-class
          • thinking-in-react-hooks
      • overreact
        • Development模式是如何工作的
        • How-Does-setState-Know-What-to-Do
        • Why-Do-React-Elements-Have-a-$$typeof-Property
        • Why-Do-React-Hooks-Rely-on-Call-Order
        • how-to-known-component-is-func-or-class
        • preparing-tach-talk-motivation
        • react作为ui运行
        • things-i-dont-known-as-2018
        • ui-element-problem-and-build-yourself
        • why-do-we-write-super-props
        • 一份完整的useEffect指南
        • 为什么X不是Hook
        • 函数组件与类有什么不同?
        • 演讲准备2-what-why-how
        • 编写弹性组件
        • 让setInterval在React-Hooks中为声明式
      • practice
        • render
      • react-dom
        • basic
      • react-redux
        • apiv7.1-hooks
        • connect
        • shallow-equal
      • redux
        • applyMiddleware
        • applyMiddleware2-细节
        • example
    • regex
      • index
    • stories
      • 数组下标
      • 阻止事件冒泡
    • svelte
      • compile-svelte-in-your-head-1
      • compiler-overview
      • parser
        • 写一个解析器-JavaScript的JSON解析器
    • turbopack
      • basic
    • typescript
      • interface和type的区别
    • webpack
      • hash
      • webpack4-for-react
      • webpack4
      • webpack4to5
      • babel
        • babel-parser和acorn的区别
        • babel.7.11
        • family
        • react16.14使用new-transform
        • update-to-7
    • pdf
      • deep-js
        • basic
      • react
        • reintroducing
  • git
    • capital
    • emoji
  • http
    • http2.0
    • response
  • rails
    • api
    • flash
    • middleware-vs-metal
    • model
    • performance
    • routes
    • environment
      • error
    • patterns
      • service
    • sidekiq
      • params
    • deploy
      • capistrano
        • ssh
  • ruby
    • self
    • net
      • http请求携带cookie
  • server
    • ss
    • ssh
    • user
    • crawler
      • puppeteer
    • nginx
      • domain-without-80
      • nginx节省带宽
  • sql
    • rails
    • search
Powered by GitBook
On this page
  • State Hook
  • 声明多个state
  • 什么是Hook
  • Effect Hook
  • Hooks的规则
  • Custom Hooks
  • Other Hooks
  1. front-end
  2. react
  3. hooks

overview

PreviousintroNextrules

Last updated 6 years ago

之前我们介绍了,在开始介绍api之前,现在我们先来整体的预览下这些api。 从上篇的介绍可以知道,Hook是向后兼容的,有react开发经验的你看起来会更顺畅。

是一个快节奏的概述。如果你感到困惑,可以看下上面提到的介绍里的动机:

详细说明 以了解我们为何将Hooks引入React。

State Hook

看下面的例子,他是一个计数器

import { 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>
  );
}

useState的唯一参数是初始状态。 在上面的例子中,它是0,因为我们的计数器从零开始。请注意,与this.state不同,此处的状态不必是对象 - 尽管可以是任何你想要的。初始状态参数仅在第一次渲染期间使用。

声明多个state

你可以在一个组件中多次使用State Hook:

function ExampleWithManyStates() {
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}

什么是Hook

React提供了一些像useState这样的内置Hook。你还可以创建自定义Hook以在不同组件之间重用有状态行为。我们先来看看内置的Hooks。

Effect Hook

你之前可能已经从React组件执行数据提取,订阅或手动更改DOM。我们将这些操作称为“副作用”(或简称为“效果”),因为它们会影响其他组件,并且在渲染过程中无法完成。

例如,下面的组件将在React更新DOM后设置文档标题:

import { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // 类似componentDidMount 和 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>
  );
}

Effects还可以通过指定返回函数来清理他们。看下面的这个例子:

import { 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';
}

就像使用useState一样, 你也可以在组件中使用多个效果:

function FriendStatusWithCounter(props) {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  const [isOnline, setIsOnline] = useState(null);
  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }
  // ...
}

Hooks允许你通过哪些部分相关(例如添加和删除订阅)来组织组件中的副作用,而不是基于生命周期方法强制拆分。

Hooks的规则

钩子是JavaScript函数,但它们强加了两个额外的规则:

  • 只能在顶层调用Hooks。不要在循环,条件或嵌套函数中调用Hook

  • 仅从React功能组件调用Hooks。 不要从常规JavaScript函数中调用Hook。 (还有另一个有效的地方叫Hooks - 你自己的定制Hooks。我们马上就会了解它们。)

Custom Hooks

import { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }

  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  });

  return isOnline;
}

它将friendID作为参数,并返回我们的朋友是否在线。 现在我们可以从两个组件中使用它:

function FriendStatus(props) {
  const isOnline = useFriendStatus(props.friend.id);

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}
function FriendListItem(props) {
  const isOnline = useFriendStatus(props.friend.id);

  return (
    <li style={{ color: isOnline ? 'green' : 'black' }}>
      {props.friend.name}
    </li>
  );
}

这些组件的状态是完全独立的。钩子是重用有状态逻辑的一种方式,而不是状态本身。 事实上,每次调用Hook都有一个完全隔离的状态 - 所以你甚至可以在一个组件中使用相同的自定义Hook两次。

custom hook更像是一种约定而非功能。如果函数的名称以use开头并且它调用其他Hook,我们说它是一个Custom Hook。useSomething命名约定是linter插件如何使用Hooks在代码中查找错误的。

Other Hooks

function Example() {
  const locale = useContext(LocaleContext);
  const theme = useContext(ThemeContext);
  // ...
}
function Todos() {
  const [todos, dispatch] = useReducer(todosReducer);
  // ...
}

在这里useState是一个Hook(我们将在稍后讨论这意味着什么)。可以看到,在这个函数组件里,我们向他添加一些本地状态。React将在重新渲染之间保留这状态。 useState返回一对:当前状态值(count)和允许你更新状态的函数(setCount)。你可以从事件处理程序或其他位置调用此函数。这个函数类似于类中的this.setState,但是它不会将旧状态和新状态合并在一起。(我们将在中显示一个将useState与this.state进行比较的示例。)

语法允许我们为通过调用useState声明的状态变量赋予不同的名称。这些名称不是useState API的一部分。相反,React假定如果多次调用useState,则在每次渲染期间以相同的顺序执行。我们将回到为什么这种方法有效以及何时有用。

钩子是允许从功能组件(function component)“挂钩”React状态和生命周期功能的功能。钩子在类内部不起作用 - 它们允许你在没有类的情况下使用React。 (我们你在一夜之间重写现有组件,但如果你愿意,可以开始在新组件中使用Hook。)

详细说明 你可以在中了解更多信息。

Effect Hook中的useEffect增加了在功能组件执行副作用的功能。它与React类中的componentDidMount,componentDidUpdate和componentWillUnmount具有相同的用途,但统一为单个API。(我们将在时显示将useEffect与这些方法进行比较的示例。)

当你调用useEffect时,你就在告诉react运行你的‘效果’函数当刷新对DOM的更改后(你可以认为是render之后)。 效果在组件内声明,因此可以访问其props和state。默认情况下,React在每次渲染后运行效果 - 包括第一次渲染。 (我们将更多地讨论与类生命周期的比较。)

在这个示例中,当组件卸载时,以及在由于后续渲染而重新运行效果之前,React将取消订阅我们的ChatAPI。(如果你愿意的话,如果我们传递给ChatAPI的props.friend.id没有改变,有办法。)

详细说明 你可以在中了解更多信息。

详细说明 你可以在中了解更多信息。

有时,我们希望在组件之间重用一些有状态逻辑的部分。传统上,这个问题有两个流行的解决方案:和。Custom Hooks允许你执行这样的操作,并且无需向树中添加更多组件。在上面我们介绍了一个调用useState和useEffect Hooks的FriendStatus组件来订阅朋友的在线状态。假设我们还希望在另一个组件中重用此订阅逻辑。 首先,我们将这个逻辑提取到一个名为useFriendStatus的自定义Hook中:

详细说明 你可以在中了解更多信息。

你可能会发现一些不太常用的内置Hook很有用。例如,允许订阅React上下文而不引入嵌套:

允许使用reducer管理复杂组件的本地状态:

详细说明 你可以在 .中了解更多信息。

,欢迎watch

使用hooks的原因
阅读动机
使用State Hook
数组解构
不建议
使用State Hook
使用Effect Hook
使用effect hook
告诉React跳过重新订阅
使用Effect Hook
Rules Hook
高阶组件
渲染道具
Writing Custom Hooks
useContext
useReducer
Hooks API Reference
hooks系列地址
本文原文档