React learning notes - extended content

Posted by Yaak on Thu, 03 Mar 2022 15:52:58 +0100

1. setState

There are two ways to update the state using setState.

Object expression is the abbreviation of function expression (syntax sugar).

Use principle (not required):

  • The new state does not depend on the original state = = > use object
  • The new state depends on the original state = = = > use functional expression
  • If you need to get the latest state data after setState() is executed, you need to read it in the callback function

1. Object type

setState(stateChange, [callback]);
  • stateChange is a state change object (this object can reflect the state change)
  • Callback is an optional callback function. It is called only after the status is updated and the interface is updated (after render is called)
  • The status update is asynchronous. If you want to view the updated status, you need to write it in the callback
const { count } = this.state;
this.setState({ count: count + 1 }, () => {
    console.log(this.state.count);
});

2. Function formula

setState(updater, [callback]);
  • updater is a function that returns the stateChange object and can receive state and props

  • Callback is an optional callback function. It is called only after the status is updated and the interface is updated (after render is called)

this.setState((state, props) => ({ count: state.count + 1 }));

2. lazyLoad of routing component

Dynamically load the routing component through the lazy function of React and the import() function to package the routing component code separately.

import Loading from './Loading';
const Home = lazy(() => import('./Home'));
const About = lazy(() => import('./About'));

Use the < suspend > tag to specify that a user-defined loading interface is displayed before loading the route packaging file.

<Suspense fallback={<Loading />}>
    {/* Register routing */}
    <Route path="/about" component={About} />
    <Route path="/home" component={Home} />
</Suspense>

3. Hooks

Hook is a new feature added in React 16.8.0. You can use state and other React features in function components. Here are three commonly used hooks:

  • State Hook: React.useState()
  • Effect Hook: React.useEffect()
  • Ref Hook: React.useRef()

1. State Hook

State Hook allows function components to have state and read and write state data.

const [xxx, setXxx] = React.useState(initValue); // Destructuring assignment 
  • useState()

    Parameter: the specified value is cached internally during the first initialization

    Return value: an array containing two elements. The first is the internal current status value, and the second is the function that updates the status value

  • Setxxx() can be written in two ways

    setXxx(newValue): the parameter is a non function value, which directly specifies a new status value and internally overwrites the original status value

    SetXXX (value = > newvalue): the parameter is a function that receives the original status value, returns a new status value, and internally overwrites the original status value

function Demo() {
    const [count, setCount] = React.useState(0);

    //Added callback
    function add() {
        // The first way to write
        // setCount(count + 1);
        // The second way to write
        setCount(count => count + 1);
    }

    return (
        <div>
            <h2>The current summation is:{count}</h2>
            <button onClick={add}>Point me+1</button>
        </div>
    );
}

2. Effect Hook

Effect Hook can perform side-effect operations in function components (used to simulate life cycle hooks in class components).

Side effects in React:

  • Send ajax request for data acquisition
  • Set subscription / start timer
  • Manually change the real DOM
useEffect(() => {
    // Any operation with side effects can be performed here
    // Equivalent to componentDidMount()
    return () => {
        // Execute before component uninstallation
        // Do some finishing work here, such as clearing timer / unsubscribing, etc
        // Equivalent to componentWillUnmount()
    };
}, [stateValue]); // Listen for stateValue
// If the array is omitted, all States are detected, and the callback function is called again when the state is updated
// If [] is specified, the callback function will only be executed after the first render()

useEffect() can be regarded as a combination of the following three functions:

  • componentDidMount()
  • componentDidUpdate()
  • componentWillUnmount()
function Demo() {
    const [count, setCount] = React.useState(0);

    React.useEffect(() => {
        let timer = setInterval(() => {
            setCount(count => count + 1);
        }, 500);
        console.log('@@@@');
        return () => {
            clearInterval(timer);
        };
    }, [count]);
    // Detect the change of count and output '@ @ @' every time

    //Added callback
    function add() {
        // The first way to write
        // setCount(count + 1);
        // The second way to write
        setCount(count => count + 1);
    }

    // Callback for unloading components;
    function unmount() {
        ReactDOM.unmountComponentAtNode(document.getElementById('root'));
    }

    return (
        <div>
            <h2>The current summation is:{count}</h2>
            <button onClick={add}>Point me+1</button>
            <button onClick={unmount}>Uninstall components</button>
        </div>
    );
}

3. Ref Hook

Ref Hook can store / find tags or any other data in the function component.

Save label object, function and react Createref()

const refContainer = useRef();
function Demo() {
    const myRef = React.useRef();

    //Callback prompting for input
    function show() {
        alert(myRef.current.value);
    }

    return (
        <div>
            <input type="text" ref={myRef} />
        </div>
    );
}

4. Fragment

After using < fragment > < fragment >, you don't have to have a real DOM root tag.

import React, { Component, Fragment } from 'react';

export default class Demo extends Component {
    render() {
        return (
            <Fragment key={1}>
                <input type="text" />
                <input type="text" />
            </Fragment>
        );
    }
}

You can also use the empty label < > < / > package. Their differences are as follows:

  • < fragment > < fragment >: can receive key attributes, but cannot receive other attributes
  • < > < / >: attribute cannot be accepted

5. Context

A communication mode between components, which is often used for communication between progenitor components and descendant components.

Create a Context container object outside the component:

const XxxContext = React.createContext();

When rendering subgroups, wrap xxxcontext Provider, which passes data to descendant components through the value attribute:

<XxxContext.Provider value={data}>
    Subcomponents
</XxxContext.Provider>

Data read by descendant components:

Mode (1), applicable only to class components:

static contextType = xxxContext  // Claim receive context
console.log(this.context); // Read value data in context

In mode (2), both function components and class components can:

<XxxContext.Consumer>
    {
        value => `${value.username},Age is ${value.age}`
    }
</XxxContext.Consumer>

Topics: Javascript Front-end React