Knowledge points of react article lesson1

Cross level data transmission

Use of context

  • Step 1: create a context object

    const MyContext = React.createContext();
    export default MyContext;
  • The second step is to use the provider to transfer data

    export default const Index = (props) => {
     const [data] = React.useState({});
     return <MyContext.Provider value={data}>

    Note that the data here should be a status of the Index component, so as to avoid that every time the Index is refreshed, the data is regenerated, resulting in the sub components also diff, explicate.

  • Child component consumption value
    There are three ways to consume the value of context;
  • contextType
class MyClass extends React.Component {
  componentDidMount() {
    let value = this.context;
    /* After the component is mounted, use the value of the MyContext component to perform some side effects */
  componentDidUpdate() {
    let value = this.context;
    /* ... */
  componentWillUnmount() {
    let value = this.context;
    /* ... */
  render() {
    let value = this.context;
    /* Render based on the value of the MyContext component */
MyClass.contextType = MyContext;

Note: you can only subscribe to a single context through this API. If you want to subscribe to more than one, please use Cunsumer. If you are using experimental   public class fields syntax , you can use   static   This class property to initialize your   contextType.

class MyClass extends React.Component {
  static contextType = MyContext;
  render() {
    let value = this.context;
    /* Render based on this value */
  1. Cunsumer

      {value => /* Rendering based on context value*/}

    This method requires a function as a child . This function receives the current context value and returns a React node. Passed to function   value   The value is equivalent to the value provided by the Provider closest to the context above the component tree   value   Value. If there is no corresponding Provider, value   Parameter is equivalent to passing to   createContext()   of   defaultValue.

  2. useContext
    It is easy to use, but it can only be used in hook syntax:
function ShowAn(){
//Call useContext and pass in the context object obtained from MyContext.
  const value = useContext(MyContext);
      the answer is {value}

More detailed contents can be referred to react official documents

Publish subscribe mode

This is not a cliche. You can understand everything. To put it simply, press the data into the queue in the subscription phase, and traverse the queue to get the desired results for operation when publishing;
What I want to say here is that one detail we should pay attention to when writing the code of publish subscribe mode is that there is also unsubscribing in pairs with subscriptions. Only when the unsubscribing program is written can it be optimized to a certain extent.
We can do this in the function of the push phase in the function of the re subscription phase,

const subscribe = (data) => {
    return () => {
        Array = Array.filter(item => item !== data);
// Then write this in the place where the subscription function is called
const unsubscribe = subscribe(data);

When we want to unsubscribe, is it convenient to call unsubscribe() directly! Take a closer look to see if it is very similar to the use of useEffect in hook syntax.

One more thing

Today, I saw an interesting blog about asynchronous interrupt. At the beginning, I talked about ajax, axios and fetch timeout of jq. The previous ones are relatively simple. ajax has. abort() function. axios already has a time field, and fetch can also be interrupted. Just need an AbortController object to obtain signal and pass this signal object as a fetch option.

async function fetchWithTimeout(timeout, resoure, init = {}) {
    const ac = new AbortController();
    const signal = ac.signal;
    const timer = setTimeout(() => {
        console.log("It's timeout");
        return ac.abort();
    }, timeout);
    try {
        return await fetch(resoure, { ...init, signal });
    } finally {

Here's the point (click on the blackboard to draw knowledge points). Everything can timeout. Axios and fetch both provide a way to interrupt asynchronous operation, but what should we do for an ordinary Promise without abort capability?
A very ingenious solution is given in this paper;
Promise doesn't have the abort capability, but we can use the. race method to interrupt it. race means racing, so is the behavior of Promise.race() well understood?

function waitWithTimeout(promise, timeout, timeoutMessage = "timeout") {
    let timer;
    const timeoutPromise = new Promise((_, reject) => {
        timer = setTimeout(() => reject(timeoutMessage), timeout);

    return Promise.race([timeoutPromise, promise])
        .finally(() => clearTimeout(timer));    // Don't forget to clear the timer

Tags: Front-end React Context

Posted on Wed, 24 Nov 2021 11:51:09 -0500 by gnunoob