简介

Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。

使用 State Hook

import React, { useState } from 'react';

function Example() {
    const [count, setCount] = useState(0);
    return (
        <div>
            <p>你点击了 {count} 次</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

使用Effect Hook

Effect Hook 可以让你在函数组件中执行副作用操作

import React, { useState,userEffect } from 'react';

function Example() {
    const [count, setCount] = useState(0);
    userEffect(()=>{
        document.title = `你点击了${count}次`
    })
    return (
        <div>
            <p>你点击了 {count} 次</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

模拟生命周期

  1. 参数一:表示回调函数

  2. 参数二:表示什么数据改变之后会触发回调函数;
    若没有参数二,表示所有数据改变都会触发 --componentDidUpdate
    参数二为空数组,表示只有在第一次组件初始化的时候会触发 --componentDidMount
    若参数二中的数组有值,表示数组中的数据发生改变之后会触发 --shouldComponentUpdate
    最后返回一个函数 --componentWillUnmount
    下面是官方文档的例子

    useEffect(() => {
      function handleStatusChange(status) {
        setIsOnline(status.isOnline);
      }
    
      ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
      return () => {
        ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
      };
    });

其他API--摘抄自官方文档

useReducer

const [state, dispatch] = useReducer(reducer, initialArg, init);

const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    </>
  );
}

useCallback

把内联回调函数及依赖项数组作为参数传入 useCallback,它将返回该回调函数的 memoized 版本,该回调函数仅在某个依赖项改变时才会更新。当你把回调函数传递给经过优化的并使用引用相等性去避免非必要渲染(例如 shouldComponentUpdate)的子组件时,它将非常有用。

const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b],
);