After three minutes

background

Before introducing Hooks, let's first talk about the creation methods of React components. One is class components and the other is pure function components. Moreover, the React team hopes that the components will not become complex containers, and it is better to just be the pipeline of data flow. Developers can combine pipelines as needed. In other words, the best way to write a component should be a function, not a class.
However, we know that in previous development, there are great differences between class components and pure function components. Pure function components have many characteristics that class components do not have:

A pure function component has no state
Pure functional components have no lifecycle
Pure function components do not have this

It is doomed that the function components we advocate can only be used for UI display, which involves state management and switching. We have to use class components or Redux, but we know that class components also have disadvantages. For example, when encountering a simple page, the code will appear heavy, and each class component is created to inherit a React instance; As for Redux, not to mention, the author of Redux said a long time ago that "problems that can be solved with React do not need Redux".

useState

useState(): status hook. Pure function components have no state. useState() is used to introduce state for function components.

Click Add one effect, which is realized by class components and function components respectively. You can see that the code written in hooks is more streamlined.
const [count,setCount] = useState(0);// Array deconstruction is equivalent to the following three sentences
let _useState = useState(0);
let count = _useState[0];
let setState = _useState[1]

Class component

import React,{Component} from "react";
class App1 extends Component{
    constructor(props) {
        super(props);
        this.state={
            count:0
        }
    }
    addCount(){
        this.setState({count:this.state.count+1})
    }
    render() {
        return(
            <div>
                <p>you clicked {this.state.count} times</p>
                <button onClick={this.addCount.bind(this)}>Click me</button>
            </div>
        )
    }

}
export default App1;

Function component

Use sueState to override the above counting component.

import React,{useState} from "react";
function App2(){
    const [count,setCount] = useState(0);//Array deconstruction
    return(
        <div>
            <p>You cliked {count} times</p>
            <button onClick={()=>{setCount(count+1)}}>Click me</button>
        </div>
    )
}
export default App2;

Multi state declaration

Use multiple statements to declare different states

import React,{useState} from "react";
function App3(){
    const [name,setName] = useState('Liu Bei');//Array deconstruction
    const [age,setAge] = useState(25);
    const [sex,setSex] = useState('male')
    return(
        <div>
            <p>full name:{name}</p>
            <p>Age:{age}</p>
            <p>Gender:{sex}</p>
        </div>
    )
}
export default App3;

useEffect

useEffect(): side effect hook. It can be used to better deal with side effects, such as asynchronous requests. Hooks' useeffect () also provides hooks for function components to deal with side effects. In class components, we will put the request in componentDidMount. In function components, we can use useeffect ().

useEffect is equivalent to componentDidMount and componentDidUpdate.
Disadvantages: because it is asynchronous, it cannot be processed in real time.

componentDidMount and componentDidUpdate in class components

import React,{Component} from "react";
class App4 extends Component{
    constructor(props) {
        super(props);
        this.state={
            count:0
        }
    }
    componentDidMount() {
        console.log(`componentDidMount=>you clicked ${this.state.count}`)
    }
    componentDidUpdate() {
        console.log(`componentDidUpdate=>you clicked ${this.state.count}`)
    }

    addCount(){
        this.setState({count:this.state.count+1})
    }
    render() {
        return(
            <div>
                <p>you clicked {this.state.count} times</p>
                <button onClick={this.addCount.bind(this)}>Click me</button>
            </div>
        )
    }

}
export default App4;

useEffect simulates componentDidMount and componentDidUpdate in class components

import React,{useState,useEffect} from "react";
function App5(){
    const [count,setCount] = useState(0);//Array deconstruction
    useEffect(()=>{
        console.log(`useEffect=>you clicked ${count} times`)
    })
    return(
        <div>
            <p>You cliked {count} times</p>
            <button onClick={()=>{setCount(count+1)}}>Click me</button>
        </div>
    )
}
export default App5;

useEffect implements componmentWillUnment

First write two route jump pages and configure the route

import React,{useState,useEffect} from "react";
import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom'
function Index(){
    return <h2>Index page</h2>
}

function List(){
    return <h2>List page</h2>
}

function App5(){
    const [count,setCount] = useState(0);//Array deconstruction
    return(
        <div>
            <div>
                <p>You cliked {count} times</p>
                <button onClick={()=>{setCount(count+1)}}>Click me</button>
            </div>
            <Router>
                    <div>
                        <ul>
                            <li><Link to="/">home page</Link></li>
                            <li><Link to="/list/">list</Link></li>
                        </ul>
                        <Routes>
                            <Route path="/" exact element={<Index/>}/>
                            <Route path="/list/" element={<List/>}/>
                        </Routes>

                </div>
            </Router>
        </div>
    )
}
export default App5;

Use useEffect to indicate the status of entering the page.
Use return when unbinding. At this time, we find that when we click the button, it will also change. This is because as long as the component changes, it will trigger unbinding. The solution uses the second parameter.

import React,{useState,useEffect} from "react";
import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom'
function Index(){
    useEffect(()=>{
        console.log(`useEffect=>Index page`)
        return ()=>{
            console.log('Jump page')
        }
    })
    return <h2>Index page</h2>
}

function List(){
    useEffect(()=>{
        console.log(`useEffect=>List page`)
    })
    return <h2>List page</h2>
}

function App5(){
    const [count,setCount] = useState(0);//Array deconstruction
    return(
        <div>
            <div>
                <p>You cliked {count} times</p>
                <button onClick={()=>{setCount(count+1)}}>Click me</button>
            </div>
            <Router>

                    <div>
                        <ul>
                            <li><Link to="/">home page</Link></li>
                            <li><Link to="/list/">list</Link></li>
                        </ul>
                        <Routes>
                            <Route path="/" exact element={<Index/>}/>
                            <Route path="/list/" element={<List/>}/>
                        </Routes>

                </div>
            </Router>
        </div>
    )
}
export default App5;

The second parameter is an array. If the array is empty, it means that the page is destroyed and triggered. If there is a variable, it means that only the state change of this variable will be triggered.

import React,{useState,useEffect} from "react";
import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom'
function Index(){
    useEffect(()=>{
        console.log(`useEffect=>Index page`)
        return ()=>{
            console.log('Jump page')
        }
    },[])
    return <h2>Index page</h2>
}

function List(){
    useEffect(()=>{
        console.log(`useEffect=>List page`)
    })
    return <h2>List page</h2>
}

function App5(){
    const [count,setCount] = useState(0);//Array deconstruction
    return(
        <div>
            <div>
                <p>You cliked {count} times</p>
                <button onClick={()=>{setCount(count+1)}}>Click me</button>
            </div>
            <Router>

                    <div>
                        <ul>
                            <li><Link to="/">home page</Link></li>
                            <li><Link to="/list/">list</Link></li>
                        </ul>
                        <Routes>
                            <Route path="/" exact element={<Index/>}/>
                            <Route path="/list/" element={<List/>}/>
                        </Routes>

                </div>
            </Router>
        </div>
    )
}
export default App5;

Parent child component value passing useContext

useContext(): shared status hook. The function is to distribute the status in react16 Support after X, avoiding react transferring data layer by layer through Props.

Use steps
1. First use createContext to create a context
2. Then use the Provider to provide the value to
3. When receiving, use useContext to receive

import React,{useState,createContext,useContext} from "react";
const CountContext = createContext();
function Counter(){
    let count = useContext(CountContext);
    return (<h2>{count}</h2>)
}
function App6(){
    const [count,setCount] = useState(0);//Array deconstruction
    return(
        <div>
            <p>You cliked {count} times</p>
            <button onClick={()=>{setCount(count+1)}}>Click me</button>
            <CountContext.Provider value={count}>
                <Counter/>
            </CountContext.Provider>
        </div>
    )
}
export default App6;

useReducer

useReducer(): action hook. In the process of using React, if you encounter state management, you will generally use redux, while React itself does not provide state management. Usereducer () provides state management. First of all, as we all know about redux, its principle is that the user initiates an action in the page, so as to change the state through the reducer method, so as to realize the communication between the page and the state. The form of reducer is (state, action) = > newstate.

import React,{useReducer} from "react";
function Reduser(){
    const [count,dispath] = useReducer((state,action)=>{
        switch (action){
            case "add":
                return state+1
            case "sub":
                return state-1
            default:
                return state
        }
    },0)
    return(
        <div>
            <h2>Now the score is{count}</h2>
            <button onClick={()=>{dispath('add')}}>add</button>
            <button onClick={()=>{dispath('sub')}}>sub</button>
        </div>
    )

}
export default Reduser

Keywords: Javascript Front-end React

Added by mystrymaster on Thu, 10 Mar 2022 03:06:47 +0200