Skip to content

React Hook 学习笔记 #30

Open
Open

Description

@QC-L

React Hook 学习笔记

阅读 React Hook 简介

  1. 可以在 class 以外的地方使用 state 等特性,例如,在函数组件中使用 state。
  2. React Native 将在下一个稳定版支持 Hook
  3. Hook 优势
    • API 完全可选
    • 向后兼容
    • 16.8.0 版本可用
    • 渐进式,可与已有代码协同
  4. 不会因为 Hook 就将 class 组件从 React 中移除。
  5. Hook 会更有助于你理解 React,提供了强大的 API,以便于你更好的组合已知的 React 特性。
  6. Hook 主要解决的问题:
    • 组件间状态难以复用,而使用 HOC 或者 Render Props 对项目侵入性又很大,会有嵌套地狱的问题。
    • 为复杂的组件解耦,减轻组件生命周期的压力。
    • class 是学习 React 的困难之一,还有 JavaScript 中 this 的指向问题。
    • 何时使用函数组件,何时使用 class 组件的分歧

阅读 React Hook 概览

  1. State Hook 的示例。可以在函数组件中使用 state。

     import React, { useState } from 'react';
    
     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>
         );
     }
    
  2. 阅读示例,其中 useState 就是 Hook。参数为 state 的初始值。

  3. 声明多个 state,其中 useState 语法用到了数组解构,这样可以为 state 起名字。

    function ExampleWithManyStates() {
       // 声明多个 state 变量!
       const [age, setAge] = useState(42);
       const [fruit, setFruit] = useState('banana');
       const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
       // ...
    }
    
  4. Effect Hook 的示例。可以在函数组件中增加操作副作用相关的能力。

    import React, { useState, useEffect } from 'react';
    
     function Example() {
         const [count, setCount] = useState(0);
    
         // 相当于 componentDidMount 和 componentDidUpdate:
         useEffect(() => {
             // 使用浏览器的 API 更新页面标题
             document.title = `You clicked ${count} times`;
         });
    
         return (
             <div>
                 <p>You clicked {count} times</p>
                 <button onClick={() => setCount(count + 1)}>
                     Click me
                 </button>
             </div>
         );
     }
    
  5. 调用 useEffect 可以生成副作用函数。

  6. 在函数组件中可以实现副作用函数相关事情,比如异步请求等。

  7. 使用 useEffect 时返回一个函数,可以清除副作用。

     useEffect(() => {
         ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    
         return () => {
             ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
         };
     });
    
  8. 副作用函数 useEffect 与 useState 相同,都可以多次调用。

  9. Hook 的使用规则

    • 只能应用于函数体最外层(即不能应用于循环,条件及子函数中)
    • 只能在函数组件中使用 Hook
  10. 创建自己的 Hook
    官方给出的自定义 Hook 的例子,这是一段抽离状态逻辑的代码,可以实现在多个函数组件中复用。
    这点在 class 组件中无法做到

    import React, { 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;
    }
    
  11. 自定义 Hook 其实就是官方 Hook 的组合体。注意:自定义 Hook 请和官方一样使用 use 开头。 useSomething 的形式。

  12. 除了 state 和 effect,官方还有其他的 Hook,如:useContent,useReducer 等。

Activity

  1. hijiangtao commented on Feb 28, 2019

    @hijiangtao

    赞啊,Hooks 和 Lifecycle 对应有一个回答解释的还错,实际使用的时候可以参考 https://stackoverflow.com/questions/53214465/how-to-use-lifecycle-methods-with-hooks-in-react/53253750#53253750

  2. changed the title [-]React Hooks 学习笔记[/-] [+]React Hook 学习笔记[/+] on Apr 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions