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
  • 等价的类示例
  • Hooks和函数组件
  • 什么是Hook
  • 声明一个状态变量
  • 读取状态
  • 更新状态
  • 概括
  • 提示:方括号意味着什么?
  • 提示:使用多个状态变量
  1. front-end
  2. react
  3. hooks

state-hook

PreviousrulesNexthooks-vs-class

Last updated 6 years ago

在之前的的里有一段代码:

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

我们将通过将此代码与等效的类示例进行比较来开始学习Hooks。

等价的类示例

看下面这段代码,你会觉得很熟悉

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

状态以{count:0}开始,当用户通过调用this.setState单击按钮时,我们会增加state.count。我们将在整个页面中使用此类的片段。

注意 你可能想知道为什么我们在这里使用计数器而不是更现实的例子。这是为了帮助我们专注于API,同时我们仍在使用Hooks迈出第一步。

Hooks和函数组件

提醒一下,React中的函数组件如下所示:

const Example = (props) => {
  // You can use Hooks here!
  return <div />;
}

或者是下面这样的:

function Example(props) {
  // You can use Hooks here!
  return <div />;
}

你可能以前将这些称为“无状态组件”。我们现在介绍的这些中具有使用React状态的能力,所以我们更喜欢名称function components。

Hook在class内 不起 作用。但是你可以使用它们而不是编写类。

什么是Hook

我们的新示例首先从React导入useState Hook:

import { useState } from 'react';

function Example() {
  // ...
}

什么是Hook? Hook是一种特殊功能,可让你“挂钩”React功能。例如,useState是一个Hook,允许你将React状态添加到函数组件。我们稍后会学习其他的Hooks。

我什么时候使用Hook? 如果你编写一个函数组件并意识到你需要为它添加一些状态,那么之前你必须将它转换为一个类。但是现在,你可以在现有功能组件中使用Hook。我们现在要做到这一点!

声明一个状态变量

在class组件中,我们声明一个状态需要向下面这样:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
 //...
}

在函数组件中,我们没有this,所以我们不能分配或读取this.state。相反,我们直接在组件内部调用useState Hook:

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);
  // ... 
}

调用useState有什么作用? 他声明了一个状态变量。我们的变量叫做count,但我们可以称之为其他任何东西,比如banana。这是一种在函数调用之间“保留”某些值的方法 - useState是一种使用this.state在类中提供的完全相同功能的新方法。通常,当函数退出时变量“消失”但React保留状态变量。

我们传递给useState的参数是什么? useState Hook的唯一参数是初始状态。与类不同,状态不必是对象。他可以是任何我们需要的内容,比如数字,字符串等。在我们的示例中,我们只需要一个数字来表示用户点击的次数,因此将0作为变量的初始状态。(如果我们想在状态中存储两个不同的值,我们将调用useState两次。)

useState返回的是什么? 它返回一对值:当前状态和更新状态的函数。这就是我们编写const [count,setCount] = useState(0)的原因。这与类中的 this.state.count和this.setState类似,只不过现在它们是成对的。

现在我们知道了useState Hook的作用,我们的例子应该更有意义

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);
  // ...
}

我们声明一个名为count的状态变量,并将其设置为0。React将记住重新渲染之间的当前值,并为我们的函数提供最新的值。如果我们想要更新当前count,我们可以调用setCount。

读取状态

当我们想要在类中显示当前计数时,我们读取this.state.count:

<p>You clicked {this.state.count} times</p>

在函数中,我们可以直接使用count:

<p>You clicked {count} times</p>

更新状态

在一个类中,我们需要调用this.setState来更新count状态:

<button onClick={() => this.setState({ count: this.state.count + 1 })}>
    Click me
</button>

在函数中,我们已经将setCount和count作为变量,因此我们不需要this:

<button onClick={() => setCount(count + 1)}>
    Click me
</button>

概括

现在让我们回顾一下我们逐行学习的内容并检查我们的理解。

 1:  import { useState } from 'react';
 2: 
 3:  function Example() {
 4:    const [count, setCount] = useState(0);
 5:
 6:    return (
 7:      <div>
 8:        <p>You clicked {count} times</p>
 9:        <button onClick={() => setCount(count + 1)}>
10:         Click me
11:        </button>
12:      </div>
13:    );
14:  }
  • 第1行: 我们从React导入useState Hook。它允许我们将本地状态保存在功能组件中。

  • 第2行: 在Example组件中,我们通过调用useState Hook来声明一个新的状态变量。它返回一对值,我们给它们命名。我们调用变量count,因为它包含按钮点击次数。

    我们通过传递0作为唯一的useState参数将其初始化为零。第二个返回的项本身就是一个函数。它允许我们更新count,因此我们将其命名为setCount。

  • 第9行: 当用户点击时,我们使用新值调用setCount。然后,React将重新呈现Example组件,并将新count值传递给它。

一开始看起来似乎有很多东西需要考虑。不要急于求成!如果你在解释有不了解的,请再次查看上面的代码并尝试从上到下阅读。我们保证,一旦你试图“忘记”状态如何在class上工作,并以新的角度看待这个代码,它就会有意义。

提示:方括号意味着什么?

当我们声明一个状态变量时,你可能已经注意到方括号:

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

左侧的名称不是React API的一部分。你可以命名自己觉得合适的状态变量:

const [fruit, setFruit] = useState('banana');
var fruitStateVariable = useState('banana'); // Returns a pair
var fruit = fruitStateVariable[0]; // First item in a pair
var setFruit = fruitStateVariable[1]; // Second item in a pair

当我们使用useState声明一个状态变量时,它返回一对 - 一个包含两个项的数组。第一项是当前值,第二项是允许我们更新第一项值的函数。使用[0]和[1]访问它们有点令人困惑,因为它们具有特定含义。这就是我们使用数组解构的原因。

提示:使用多个状态变量

将状态变量声明为一对[something,setSomething]也很方便,因为如果我们想要使用多个状态变量,它可以让我们为不同的状态变量赋予不同的名称:

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

在上面的组件中,我们将age,fruit和todos作为局部变量,我们可以单独更新它们:

function handleOrangeClick() {
    // Similar to this.setState({ fruit: 'orange' })
    setFruit('orange');
  }

你 不必使用 许多状态变量。 状态变量可以很好地保存对象和数组,因此仍然可以将相关数据组合在一起。但是,与类中的this.setState不同,更新状态变量总是替换它而不是合并它。

注意: 关于在何处可以使用Hook并且不能在组件中使用Hook,有一些特殊规则。我们将在“”中学习它们。

注意 你可能想知道:为什么useState没有命名为createState?“create”不会非常准确,因为状态仅在我们的组件第一次呈现时创建。在下一次渲染期间,useState为我们提供了当前状态。否则它根本不会是“状态”!Hook名称总是从use开始也是有原因的。我们将在后来的中了解原因。

此JavaScript语法称为“”。这意味着我们正在创建两个新变量fruit和setFruit,其中fruit设置为useState返回的第一个值,setFruit是第二个。等同于下面的代码:

注意: 你可能很好奇React如何知道哪个组件useState对应,因为我们没有将这样的任何内容传递给React。我们将在FAQ部分回答和许多其他问题。

我们中提供了有关拆分独立状态变量的更多建议。

hook 介绍
钩子规则
rules hooks
数组解构
这个问题
在FAQ
本文原文地址