React practice is essential to note (15) - React Hooks

  Hook (hook) is newly introduced React v16.8 characteristic, feature state can function as an additional component class component, life cycle form of a hook. React class components are difficult to split test, the dispersion state logic, it is difficult to reuse problems, although the logic state may be extracted by rendering properties (Render Props) and higher order components, but nested layers are formed, used Hook after the function of the components will be able to avoid these problems.

  JavaScript is a special function of the nature Hook, to use the name prefix in use it follows two rules, listed below:

  (1) Hook calls in loops, conditional statements or nested function is not allowed to be at the top level function calls, be sure to call in order Hook.

  (2) can only be invoked in React Hook function or custom components in Hook.

  These two rules can be combined with text analysis gradually began to feel, the next will explain in detail several built-in Hook, and will explain how to customize the sample Hook, the text comes from the official website .

A, State Hook (hook state)

  First look at a simple class components, Btn components will render a button, every click of a button, the text of which will be a plus.

import React from "react";
class Btn extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0
    };
    this.dot = this.dot.bind(this);
  }
  dot() {
    this.setState({ count: this.state.count + 1 })
  }
  render() {
    return <button onClick={this.dot}>{this.state.count}</button>;
  }
}

  Then the functional form Btn assembly into the same functions, as shown in the following code, and constructors not render () method, by useState () is a function of the state of the additional components.

import { useState } from "react";
function Btn() {
  const [count, setCount] = useState(0);
  return (<button onClick={() => setCount(count + 1)}>{count}</button>);
}

  useState () is a hook function, which is the initial value of the parameter of state, returns an array, it comprises two elements: the current function status, and update status. Declares a state variable called count and a function called by an array of deconstruction setCount manner equivalent to the class components and this.state.count this.setState (). Click to read status in the event or call the update function of the state you do not need this.

  Note, useState () can be called multiple times, React will ensure the independence of the state according to the order of appearance useState (), and with this.setState () it is different, update status is replaced rather than merge.

Two, Effect Hook (Hook side effects)

  There are two common side effects React component: No Clear and need to be cleared, then one by one to explain.

1) without clearing

  Will run some side effects do not need to remove the update after React DOM, for example, a data request to the server, change the DOM structure, logging and so on. In class components, these side effects often () method performed in the lifecycle componentDidMount () and componentDidUpdate. Btn one or more components of an example, after the update count, modify the page header, as shown below (only a list of core code).

class Btn extends React.Component {
  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }
  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }
}

  Note that the two functions are repeated in the code, because in many cases, when the assembly is mounted, and performs the same update operation, and does not provide a function React available after each rendering callback.

  Next, with useEffect () function hooks perform the same function, the same core code lists only, the following code shown in FIG. useEffect () function so that the same do not have side effects into different life cycle, i.e. use according isolated side.

import { useEffect } from "react";
function Btn() {
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
}

  useEffect () may receive two parameters, the first parameter is a callback function called Effect, Effect will be executed after each rendering (including the first mount and subsequent update DOM), which are each received Effect are new, have to worry about the state expired; second parameter is optional array (by the composition dependency Effect) for performing control of Effect, and will depend on whether Effect elements in the array has occurred change, as for example, the count variable element of the array (as shown in the code), when the same count value after the count value of the re-rendering, this ignores React Effect, to optimize performance.

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

  When the empty array ([]) passed useEffect (), Effect run only once, i.e. only when the running assembly mount and unmount. Effect Since any value or state does not depend on the props, and therefore never need to repeat.

  A combination of three life-cycle approach useEffect () equivalent componentDidMount (), componentDidUpdate () and componentWillUnmount (), but componentDidMount () or componentDidUpdate () different, use useEffect () will be executed asynchronously side effects, can avoid blocking browser update view.

2) need to be cleared

  Some side effects and must be removed, for example, subscribe to external data sources, after it cleared to prevent memory leaks. In class components, usually () set the subscription componentDidMount, and perform cleanup in componentWillUnmount () in.

  Consider a ChatAPI module for subscription status of a friend, as shown below (only a portion of the key), wherein componentDidMount () and componentWillUnmount () associated with the side effects of treatment.

class FriendStatus extends React.Component {
  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
    });
  }
}

  Next, a function to achieve the same functionality as the components, only a key part of the same code. Due to add and remove subscriptions logic has a strong tightness, therefore useEffect () will organize them together. Effect When a function returns, it will be called React clear operation is performed, as shown below.

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

  Note, React to be cleared before executing on a current Effect Effect, that is, the side effects are not to be executed when the component is uninstalled.

Third, custom Hook

  Hook for storing custom logic reusable assembly, its parameters and return values ​​are no special requirements, like a normal function, but in order to follow the rules of Hook, the name must begin with use. The next component before FriendStatus friends subscribed to online status logic detached useFriendStatus custom (), which is a parameter friendID, the return value of the current state of friends, as shown below.

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);
  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  });
  return isOnline;
}

  Calls the custom assembly in FriendStatus Hook, its internal logic will be very simple, as shown below.

function FriendStatus(props) {
  const isOnline = useFriendStatus(props.friend.id);
  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

Fourth, other Hook

  In addition to the above two built-Hook explain, React Hook also provides other functions, e.g. useContext (), useCallback (), useMemo (), useLayoutEffect () , and specifically refer to the official API index .

1)useContext()

  Receiving a Context object () created by React.createContext, returns the current value of the Context (i.e., data to be transmitted). Call useContext () components will be re-rendered in the Context value changes.

2)useCallback()

  It includes two parameters, the first one is the callback function, the second term is dependent on the array, the memory version of the callback function returns. When a dependency changes, it updates the callback function. Note that dependency is not an array as a parameter passed to the callback function.

3) useMemo ()

  Contains callback functions and dependencies array with two parameters, the return value of the callback function is useMemo () return value, it will be cached, and it is recalculated only when a change occurs dependencies. Before useCallback (fn, deps) corresponds useMemo (() => fn, deps).

4)useLayoutEffect()

  Function signature and useEffect () the same, but different invocations opportunity, it will synchronize calls Effect After all DOM updates, that is, before the browser calls Effect update the view.

 

Guess you like

Origin www.cnblogs.com/strick/p/11937422.html