Catalog
  1. 1. Hook是什么
  2. 2. 如何使用Hook(以使用state为例)
  3. 3. Hook有哪些优势呢?
  4. 4. 推荐阅读
开始使用Hook吧

Hook是什么

  • Hook是React16.8的新增特性,提供内置钩子函数(也可自定义),它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性
  • 在以函数声名的组件中使用,不可以在class声名的组件中使用

如何使用Hook(以使用state为例)

  • 引用

    1
    import React, { useState } from 'react';
  • 定义及使用

    • 使用useState会返回两个对象

      1. 经过初始化的state
      2. 改变state的方法
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      function Example() {
      // 声明一个新的叫做 “count” 的 state 变量
      const [count, setCount] = useState(0);

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

Hook有哪些优势呢?

  1. 避免编写重复代码

    1
    2
    3
    4
    5
    6
    7
    componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
    }

    componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
    }
    1
    2
    3
    useEffect(() => {
    document.title = `You clicked ${count} times`;
    });
  2. 将紧密性强的代码放到一起执行,逻辑就会更好理解

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    componentDidMount() {
    ChatAPI.subscribeToFriendStatus(
    this.props.friend.id,
    this.handleStatusChange
    );
    }

    componentWillUnmount() {
    ChatAPI.unsubscribeFromFriendStatus(
    this.props.friend.id,
    this.handleStatusChange
    );
    }

    handleStatusChange(status) {
    this.setState({
    isOnline: status.isOnline
    });
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    useEffect(() => {
    function handleStatusChange(status) {
    setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
    ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
    });

    useEffect返回的函数会在组件卸载时执行

推荐阅读

Author: Erealm
Link: http://erealmsoft.github.io/2019/09/20/react/react-use-hook/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Comment