跟着 React 官方文档学 Hooks

这篇文章两个月以前写的,看了一下官网文档没啥变化,就发出来了。若是有什么错误,欢迎指出~html

前言:一直对这个新特性很是感兴趣,终于今天有时间,花了大半天时间,把 Hooks的官方教程过了一遍,收获颇多,惊叹这个新特性真 TM 好用,之后开发用这个怕是要起飞了😆。react

状态钩子(State Hook)

const [state, setState] = useState(initialState);
复制代码
  1. 多个useState时,React依赖于每次渲染时钩子的调用顺序都是同样的(存在与每一个组件关联的“存储单元”的内部列表存放JavaScript对象),从而实现钩子与状态的一一对应关系。
  2. setState()接收新的state或者一个返回state的函数(setCount(prevCount => prevCount - 1)})。
  3. 不一样于类组件中的setStateuseState返回的setState 不会自动合并更新对象到旧的state中(可使用useReducer)。
  4. useState能够接收一个函数返回initialState,它只会在初次渲染时被调用。
  5. setState中的state和当前的state相等(经过Object.is判断),将会退出更新。
  6. 建议将一个状态根据哪些须要值一块儿变化拆分为多个状态变量。
const [rows, setRows] = useState(createRows(props.count));  // `createRows()`每次将会渲染将会被调用
复制代码

优化一下:git

const [rows, setRows] = useState(() => createRows(props.count));  // `createRows()`只会被调用一次
复制代码

其中的() => createRows(props.count)会赋值给rows,这样就保证了只有在rows调用时,才会建立新的值。npm

做用钩子(Effect Hook)

useEffect(didUpdate);
复制代码
  1. 至关于生命周期函数componentDidMount, componentDidUpdate, componentWillUnmount的组合。
  2. 能够返回一个函数(cleanup)用于清理。
  3. 每次从新渲染都将会发生cleanup phase
useEffect(() => {
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });
复制代码
componentDidMount() {
    ChatAPI.subscribeToFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }

  // ====== 缘由在这里 ======
  componentDidUpdate(prevProps) {
    // Unsubscribe from the previous friend.id
    ChatAPI.unsubscribeFromFriendStatus(
      prevProps.friend.id,
      this.handleStatusChange
    );
    // Subscribe to the next friend.id
    ChatAPI.subscribeToFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }

  componentWillUnmount() {
    ChatAPI.unsubscribeFromFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }
复制代码
// Mount with { friend: { id: 100 } } props
ChatAPI.subscribeToFriendStatus(100, handleStatusChange);     // Run first effect

// Update with { friend: { id: 200 } } props
ChatAPI.unsubscribeFromFriendStatus(100, handleStatusChange); // Clean up previous effect
ChatAPI.subscribeToFriendStatus(200, handleStatusChange);     // Run next effect

// Update with { friend: { id: 300 } } props
ChatAPI.unsubscribeFromFriendStatus(200, handleStatusChange); // Clean up previous effect
ChatAPI.subscribeToFriendStatus(300, handleStatusChange);     // Run next effect

// Unmount
ChatAPI.unsubscribeFromFriendStatus(300, handleStatusChange); // Clean up last effect
复制代码
  1. useEffect(() => {document.title = You clicked ${count} times;}, [count]); ,指定第二个参数(这里为[count])变化时才发生cleanup phase,而后执行effect
  2. 上面状况,若是useEffect第二个参数为为[]则表示只运行一次(componentDidMount中执行effectcomponentWillUnmount中进行cleanup),永远不从新运行。
  3. componentDidMount/componentDidUpdate有区别的地方在于,useEffect中的函数会在layoutpaint结束后才被触发。(可使用useLayoutEffect在下一次渲染以前(即 DOM 突变以后)同步触发)
  4. useEffect虽然被推迟到浏览器绘制完成以后,可是确定在有任何新的呈现以前启动。由于React老是在开始更新以前刷新以前渲染的效果。

其余钩子

useContext

const context = useContext(Context);
复制代码

接受一个上下文对象(由React.createContext建立),返回当前上下文值(由最近的上下文提供)。数组

附加钩子(Additional Hooks)

基本钩子的变体或用于特定边缘状况的钩子。浏览器

useReducer

const [state, dispatch] = useReducer(reducer, initialArg, init);
复制代码
  1. 第三个参数init为函数,将会这样调用:init(initialArg),返回初始值。
  2. 若是返回state和如今的state同样,将会在不影响子孙或者触发效果的状况下退出渲染。

useCallback

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

传入一个内联回调和一个输入数组,返回一个带有记忆的函数,只有输入数组中其中一个值变化才会更改。useCallback(fn, inputs) 等价于 useMemo(() => fn, inputs)app

useMemo

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
复制代码

传入一个建立函数和一个输入数组,返回一个带有记忆的,只有输入数组中其中一个值变化才会从新计算。dom

useRef

const refContainer = useRef(initialValue);
// ...
<input ref={refContainer} />
...
复制代码

返回一个可变的ref对象,能够自动将ref对象中的current属性做为初始值传递的参数,保持到组件的整个生命周期。函数

与在类中使用实例字段的方式相似,它能够保留任何可变值布局

如保存前一个状态:

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

  const prevCountRef = useRef();
  useEffect(() => {
    prevCountRef.current = count;
  });
  const prevCount = prevCountRef.current;

  return <h1>Now: {count}, before: {prevCount}</h1>;
}
复制代码

useImperativeHandle

useImperativeHandle(ref, createHandle, [inputs])
复制代码

自定在使用 ref 时,公开给父组件的实例值,必须和forwardRef一块儿使用。

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));
  return <input ref={inputRef} ... />; } FancyInput = forwardRef(FancyInput); 复制代码
<FancyInput ref={fancyInputRef} />

// 调用
fancyInputRef.current.focus()
复制代码

useLayoutEffect

使用方法和useLayoutEffect一致,不过它是在 DOM 读取布局时同步触发(至关于componentDidMountcomponentDidUpdate阶段)。(建议尽量使用useEffect避免阻塞可视化更新)

useDebugValue

useDebugValue(value)
复制代码

用于在React DevTools中显示自定义钩子的标签,对于自定义钩子中用于共享的部分有更大价值。

自定义显示格式:

useDebugValue(date, date => date.toDateString());
复制代码

钩子(Hooks)规则

1. 只能在顶层调用,不能再循环、条件语句和嵌套函数中使用。 (缘由:[State Hook](#State Hook) 第1条)

正确作法:

useEffect(function persistForm() {
      // 👍 We're not breaking the first rule anymore
      if (name !== '') {
        localStorage.setItem('formData', name);
      }
    });
复制代码

2. 只能在React函数组件中被调用。(能够经过自定义钩子函数解决)

可使用eslint-plugin-react-hooks来强制自动执行这些规则。

自定义钩子(Hook)

  1. use开头,一种公约。
  2. 自定钩子是一种复用状态逻辑的机制(例如设置订阅和记住当前值),每次使用,内部全部状态和做用都是独立的。
  3. 自定义钩子每一个状态独立的能力源于useStateuseEffect是彻底独立的。

测试钩子(Hook)

function Example() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
  return (
    <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div>
  );
}
复制代码

使用ReactTestUtils.act()

import React from 'react';
import ReactDOM from 'react-dom';
import { act } from 'react-dom/test-utils';
import Counter from './Counter';

let container;

beforeEach(() => {
  container = document.createElement('div');
  document.body.appendChild(container);
});

afterEach(() => {
  document.body.removeChild(container);
  container = null;
});

it('can render and update a counter', () => {
  // Test first render and effect
  act(() => {
    ReactDOM.render(<Counter />, container); }); const button = container.querySelector('button'); const label = container.querySelector('p'); expect(label.textContent).toBe('You clicked 0 times'); expect(document.title).toBe('You clicked 0 times'); // Test second render and effect act(() => { button.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(label.textContent).toBe('You clicked 1 times'); expect(document.title).toBe('You clicked 1 times'); }); 复制代码

建议使用react-testing-library

参考

相关文章
相关标签/搜索