我的HOOKS学习总结

133 阅读3分钟

一、Hooks概述

Hooks 允许您在没有类的情况下使用更多 React 的功能。

特点:

  • 完全是选择性加入。如果专注于类组件,你可以无须学习hooks。(只限在函数式组件立使用)
  • 100%向后兼容。
  • 现在可用。(官方:不会删除类组件的概念)

二、使用State(状态)Hook

首先我们来看一个简单的点击计数的例子:

(1)使用hooks的useState实现

import { useState } from 'react';

function Example() {

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

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

(2)使用类组件实现

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

总结:

       在类中,我们通过在构造函数中将 this.state 设置为 { count: 0 } 来将 count state(状态) 初始化为 0 ;

       但是在函数式组件中,我们没有 this ,所以我们不能分配或读取 this.state 。所以这里我们引入使用hooks,直接在组件内部调用 useState为函数式组件添加state(状态)。

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

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

      这里useState其实就是一个函数,参数为设置的state变量的初始值,返回值为当前state(状态) 和更新它的函数。

三、使用Effect Hook

       首先了解什么是副作用(Side Effect):副作用(Side Effect)是指函数或者表达式的行为依赖于外部世界。具体可参照Wiki上的定义,副作用是指:

  • 函数或者表达式修改了它的 scope 之外的状态
  • 函数或者表达式除了返回语句外还与外部世界或者它所调用的函数有明显的交互行为

Effect Hook的作用?

Effect Hook为你的函数式组件增添了执行 side effects 的能力。
import { useState, useEffect } from 'react';

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

  // Similar to componentDidMount and 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>
  );
}

         这里,我们可以将 useEffect Hook 视为 componentDidMountcomponentDidUpdatecomponentWillUnmount 的组合。

下面具体解析这段代码:

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

       我们声明了 count state(状态)变量,然后告诉 React 我们需要使用 effect 。我们将一个函数传递给useEffect Hook,这个函数就是我们的 effect 。在我们的 effect 中,我们使用 document.title 浏览器 API 设置文档标题。我们可以读取 effect 中的最新count,因为它在我们的函数作用域内。当 React 渲染我们的组件时,它会记住我们使用的 effect ,然后在更新 DOM 后运行我们的effect 。每次渲染后都会发生,包括第一次渲染。

四、Hooks使用规则

  • 只在顶层调用hooks。不要在循环,条件或嵌套函数中调用 Hook 。 相反,总是在 React 函数的顶层使用 Hooks。 通过遵循此规则,您可以确保每次组件渲染时都以相同的顺序调用 Hook 。 这就是允许 React 在多个 useStateuseEffect 调用之间能正确保留 Hook 状态的原因。
  • **只在 React Functions 调用 Hooks。**不要在常规函数中使用。

备注:我们可以使用一个名为eslint-plugin-react-hooks 的ESLint插件,它能够帮我们强制执行这两个规则。