react3.0 - component, component value transfer, Context, component life cycle, routing, matching mode

react3.0

The variable name of global import can be customized, and the specified variable name is used for on-demand import

Review component value transfer:

Father to son, son to father:

review.js

import React from "react"
// When transferring values, pay attention to the problem of this pointing. There are three solutions: 1 Use bind in the constructor, 2 Use the arrow function during initialization, 3 Set a layer of arrow function outside the function
// Parent component
class Person extends React.Component {
    state = {
        msg:'I am the data of the parent component'
    }
    render() {
        return (
            <div>hello,Good morning
                { this.state.msg}
                <Son msg={this.state.msg} />
                { /*info It is the property bound by Child child Child components, and the property value is the callback function of the parent component, which is used to receive data*/}
                <Child info={ this.getInfo}/>
            </div>
            
        )
    }
    // Adding an event to a parent component is a callback function
    // Receive the data passed by Child and modify the value of msg in state again
    // The parameter msg is the data passed from the subcomponent
    getInfo = (msg) => {
        this.setState({
            msg:msg
        })
    }
}
// Father to son
// Subcomponents
function Son(props) {
    return (
        <div>I am Son Data passed from child component and parent component:{ props.msg}</div>
    )
}


class Child extends React.Component {
    // Add status to subcomponents
    state = {
        msg:'I'm a subcomponent Child Data'
    }
    render() {
        return (
            <div>
                I am Child Subcomponents
                { /*The msg data in the state is passed to the parent component by triggering the handle event*/}
                <button onClick={this.handle}>Pass the value to change the of the parent component msg</button>
            </div>
        )
    }
    handle = () => {
        // Through this Props calls the callback function of the parent component
        // info is a custom attribute of the tag. It is a callback function. The parameter is the data to be passed
        this.props.info(this.state.msg)
    }
}

export default Person

index.js

import React from 'react';
import ReactDOM from 'react-dom';
// Son to father, father to son
import Person from "./components/review"

ReactDOM.render(
  <div><Person/></div>,
  document.getElementById('root')
);

Value transfer between sibling components:

import React from 'react';
import ReactDOM from 'react-dom';
// Value transfer between sibling components: child to parent, parent to child combination, and value transfer through user-defined attributes
// Common component Hello
class Hello extends React.Component {
  // Public status count
  state = {
    count: 0
  }
  render() {
    return (
      <div>
        <Son1 info={ this.state.count}/>
        <Son2 info={ this.getInfo}/>
      </div>
    )
  }
  // Process count
  getInfo = () => {
    this.setState({
      count:this.state.count+1
    })
  }
}

// Son1 component: display count
class Son1 extends React.Component {
  render() {
    return (
      <div>
        { this.props.info}
      </div>
    )
  }
}
// Son2 component: operation count
class Son2 extends React.Component {
  render() {
    return (
      <div>
        <button onClick={ this.handle}>+1</button>
      </div>
    )
  }
  handle = () => {
    this.props.info()
  }
}

ReactDOM.render(
  <div><Hello /></div>,
  document.getElementById('root')
);

Context

import React from 'react';
import ReactDOM from 'react-dom';
// Provider: provide data, Consumer: use data
const {Provider,Consumer } =React.createContext()
// If you want to pass a value to a component, add a Provider tag outside the component tag. The value attribute value of the tag is the data to be passed

class Hello extends React.Component {
    state = {
        msg:'I am Provider Data provided'
    }
    render() {
        return (
            <div>
                <Provider value={this.state.msg}>
                    I am Provider label
                    <Son />
                </Provider>
                <Provider value="I am a cook, come on, work hard">
                    <Child/>
                </Provider>
            </div>
        )
    }
}
// Data provided to the user Provider
class Son extends React.Component {
    render() {
        return (
            <div>
                <Child />
                <Consumer>
                        {data => { return data}}
                </Consumer>
            </div>
        )
    }
}

class Child extends React.Component {
    render() {
        return (
            <div>
                I am Son assembly
                <Consumer>{data => { return data}}</Consumer>
            </div>
        )
    }
}


ReactDOM.render(
  <div><Hello /></div>,
  document.getElementById('root')
);

Component lifecycle

Component life cycle: the process from component creation to mounting to running in the page, and then to component unloading when not in use; Each stage of the life cycle is always accompanied by some method calls, which are the hook functions of the life cycle

Only class components have a life cycle, and function components have no life cycle

The function of hook function: it provides an opportunity for developers to operate components at different stages

Three stages of the life cycle

1. When creating (Mount phase)

Execution time: when the component is created (when the page is loaded)

Execution order of hook functions: constructor() {} - > render () {} - > componentdidmount() {}

Hook functionTrigger timingeffect
constructorWhen creating a component, execute first1. Initialize state; 2. Bind this for the event handler
renderTriggered every time a component is renderedRender UI (Note: setstate() cannot be called)
componentDidMountAfter the component is mounted (DOM rendering is completed)1. Send network request; 2.DOM operation
2. When updating (update phase)

Execution time: 1 setState(); 2.forceUpdate(); 3. The component receives a new props

Note: if any of the above three changes, the component will be re rendered

Execution sequence: render() - > componentdidupdate()

Hook functionTrigger timingeffect
renderTriggered each time a component is renderedRender UI (same render as Mount phase)
componentDidUpdateComponent update (after DOM rendering)1. Send network request; 2.DOM operation note: if you want to use setState(), you must put it in an if condition

If you want to initiate a network request, it is usually executed in componentDidMount() in the mount phase, because componentDidUpdate() is triggered only when there is an execution opportunity in the update phase

3. During unloading (unloading phase)

Execution timing: the component disappears from the page

Hook functionTrigger timingeffect
componentWillUnmountComponent uninstall (disappear from page)Perform cleaning work (such as clearing timers, removing listening events, etc.)
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            // Counter
            count: 0
        }
    }
    render() {
        return (
            <div>
                {
                    this.state.count > 5 ? <Line /> : <Counter count={this.state.count }/>
                }
                <button onClick={ this.handle}>+1</button>
            </div>
        )
    }
    // Process count
    handle = () => {
        this.setState({
            count: this.state.count+1
        })
    }
}
// After count > 5, the Line component is displayed
class Line extends React.Component {
    render() {
        return (
            <div>
                <p>Doudou went to heaven</p>
            </div>
        )
    }
}
// When count < = 5, the Counter component is displayed
class Counter extends React.Component {
    // So at this stage
    componentDidMount() {
        this.timer = setInterval(() => {
            console.log("The counter is executing");
        },1000)
    }
    render() {
        return (
            <div>
                <p>Number of times Doudou was beaten:{ this.props.count}</p>
            </div>
        )
    }
    // Unloading phase
    // This event is triggered when this component does not exist or is replaced by other components
    componentWillUnmount() {
        console.log('Doudou went to heaven, Counter Component is Line The component has been replaced and does not exist');
        clearInterval(this.timer)
    }
 }

ReactDOM.render(
    <div><App /></div>,
    document.getElementById('root')
);

React routing

SPA: single page program, that is, an application with only one html page; Better user experience and less pressure on the server, so it is more popular. A component is a page

Front end routing function: allows users to navigate from one view (page) to another

Front end routing is a set of mapping rules. In React, it is the corresponding relationship between URL path and component

Using React routing is to configure paths and components (pairing)

Use steps:

1. Installation:

yarn add react-router-dom
npm i react-router-dom

2. Import (import on demand) the three core components of Routing: router, route and link

import {BrowserRouter as Router,Route,Link } from "react-router-dom"

Router is the alias of BrowserRouter. The alias imported on demand is implemented with as, and the alias of deconstructed data is implemented with as** 😗* realization

3. Wrap the entire application with the Router component label

4. Use the Link component as the navigation menu (route entry), which is equivalent to an a tag with a to attribute (similar to the href attribute of a tag),

5. Use the Route component to configure the routing rules and the components to be used (Route exits), with path attribute and component,

<Router>
//Route entry
	<Link to="/One">reach One Component page go</Link>
	//Route exit
	<Route path='/One' component={One}></Route>
</Router>
import React from 'react';
import ReactDOM from 'react-dom';
// Import on demand
// BrowserRouter as Router: import BrowserRouter as needed. Use as to give it an alias Router
import { BrowserRouter as Router, Route, Link } from "react-router-dom"
// /One page
const One = () => {
    return (
        <div>
            I'm the first page
        </div>
    )
}
// App page
class App extends React.Component {
    render() {
        return (
            <Router>
                {/* Route entry */}
                <Link to="/One">reach One Component page go</Link>
                {/* Route exit */}
                <Route path='/One' component={One}></Route>
            </Router>
        )
    }
}


ReactDOM.render(
    <div><App /></div>,
    document.getElementById('root')
);

Description of common components

Router component: wrap the whole application. A React application only needs to be used once

There are two common routers: HashRouter and BrowserRouter

HashRouter: implemented using the hash value of the URL (localhost/#/One)

(recommended) BrowserRouter: implemented using H5's history API (localhost:3000/One)

Matching pattern

import React from 'react';
import ReactDOM from 'react-dom';
// Import on demand
// BrowserRouter as Router: import BrowserRouter as needed. Use as to give it an alias Router
import { BrowserRouter as Router, Route, Link } from "react-router-dom"
// Login page
class Login extends React.Component {
    handleLogin = () => {
        // Programming navigation
        // Jump to a page
        this.props.history.push('/home')
    }
    render() {
        return (
            <div>
                I am Login page
                <button onClick={this.handleLogin}>Home</button>
            </div>
        )
    }
}
// Home page
// Because it is a function component, all components do not have their own state
const Home = props => {
    const handleBack = () => {
        // Programming navigation
        // Back to previous page
        props.history.go(-1)
    }
    return (
        <div>
            <h3>I am Home page</h3>
            <button onClick={handleBack}>Login</button>
        </div>
    )
}
// Default displayed page
const Hello = () => {
    return (
        <div>
            <p>hello</p>
        </div>
    )
}
// App page, the whole application interface
// In the Router tab, do not make programmed navigation, because props is required, but this App is level 1, and there is no component to pass values to it, so programmed navigation cannot be realized
class App extends React.Component {
    render() {
        return (
            <Router>
                <div>
                    {/* The route entry is equivalent to an a tag*/}
                    {/*Fuzzy matching: to="/hello/login/home", originally meant to go to the home page, but the matching result is: all three pages are matched */}
                    {/*Exact match: to accurately match a page, add the exact attribute to the Route tag of the Route exit*/}
                    <Link to="/hello/login/home">Sign in</Link>
                    {/* Route exit */}
                    {/* Default route */}
                    <Route exact path='/hello' component={Hello}></Route>
                    <Route exact path='/hello/login' component={Login}></Route>
                    <Route exact path='/hello/login/home' component={Home}></Route>
                </div>
            </Router>
        )
    }
}

ReactDOM.render(
    <div><App /></div>,
    document.getElementById('root')
);

Keywords: Javascript node.js Front-end ECMAScript React

Added by edtlov on Sat, 22 Jan 2022 00:40:37 +0200