1. Introduction

Take notes as you study, and correct any mistakes you make. React-hooks are a new feature in React that only works on react16.8 and older.

2. Introduction to Hooks

Write a requirement: click the button and add 1 to the number.


import React, { Component } from 'react';
class example extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            temp:0
         };
    }
    onclick =()=>{
        this.setState({
            temp:this.state.temp+1
        })
    }
    render() {
        return (
            <div>
                <div>
                    clickResult is {this.state.temp}
                </div>
                <button onClick={this.onclick} style={{marginTop:"20px",marginBottom:"20px"}}>click</button> </div> ); }}export default example;
Copy the code

Do not create components using inherited Component, use function to create components, use useState to use and update state:

import React, { useState } from 'react';
function Example (){
    const [temp, setCount] = useState(0);
    return (
        <div>
            <div>
                clickResult is {temp}
            </div>
            <button onClick={()=>{setCount(temp+1)}} style={{marginTop:"20px",marginBottom:"20px"}}>click this</button>
        </div>
    );

export default Example;
Copy the code

3.useState

1) How to declare

const [temp,setCount] = useState(0); // On the left side, use the array destruct method, equivalent to the following:Copy the code
let _useState = useState(0);
let temp = _useState[0];
let setCount = _useState[1];
Copy the code

2) How to read

The useState function takes the Initial state and returns an array with bit 0 of the current state and bit 1 of the method function that can change the state.

Read with {XXX}Copy the code

3) How to change

In the above example, the setCount function is used to change:

onClick={()=>{setCount(temp+1)}}
Copy the code

The setCount function accepts the new state value as an argument. React is left to re-render the components. React automatically helps us remember the last state value of the component.

4) How to declare multiple states

const [ age , setAge ] = useState(18)
const [ sex , setSex ] = useState('male')
const [ work , setWork ] = useState('Front-end Programmer')
return(< div > < p > JSPang this year: {age}, < / p > < p > gender: {sex} < / p > < p > work is: {5} < / p > < / div >)Copy the code

Note that useState cannot be used in if… else… Calls to such conditional statements must be rendered in the same order. React Hooks cannot appear in conditional statements because they must have exactly the same render order and do not allow:

const [ age , setAge ] = useState(18)
if(showSex){
    const [ sex , setSex ] = useState('male')
    showSex=false
}

const [ work , setWork ] = useState('Front-end Programmer')
Copy the code

This will cause an error:

React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render 
Copy the code

4.useEffect

UseEffect is used to replace the life cycle of a component created by class:

UseEffect to implement componentDidmount and componentDidUpdate

First, the effect picture:

import React, { Component } from 'react'; class Example1 extends Component { constructor(props) { super(props); This. state = {temp:0}} //React is called at the end of a component callcomponentDidMount(){
        console.log(`ComponentDidMount=>You clicked ${this.state.temp} times')} // Component state change callcomponentDidUpdate(){
        console.log(`componentDidUpdate=>You clicked ${this.state.temp} times`)}render() { 
        return (
            <div>
                <p>You clicked {this.state.temp} times</p>
                <button onClick={this.addCount.bind(this)}>Chlick me</button>
            </div>
        );
    }
    addCount(){
        this.setState({temp:this.state.temp+1})
    }
}

export default Example1;
Copy the code

Reuse useEffect

import React, { useState,useEffect } from 'react';

function Example1 () {
    const [temp, setCount] = useState(0);
    useEffect(()=>{
        console.log(`useEffect=>You clicked ${temp} times`);
    })
    return (
        <div>
            <div>
                clickResult is {temp}
            </div>
            <button onClick={()=>{setCount(temp+1)}} style={{marginTop:"20px",marginBottom:"20px"}}>click this</button>
        </div>
    );
}
export default Example1;
Copy the code

UseEffect can replace componentDidMount and DidUpdate with only one useEffect function (didMount and DidUpdate). ② : useEffect is asynchronous. The defined function does not block the update of the browser view. If you want to calculate the page size in real time, it cannot be implemented synchronously.

UseEffect to implement componentWillUnMount function

Realize componentWillMount function is to realize the unloading function, install the route first, realize the component destruction process of component jump.

1) Install routes
npm install --save react-router-dom
Copy the code
2) Build a basic page layout
import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

function Interface() {
    return<h2> Interface test </h2>}function Group() {
    return<h2> Component test </h2>}function Example2() {
    const [temp, setCount] = useState(0);
    return (
        <div>
            <div>
                clickResult is {temp}
            </div>
            <button onClick={() => { setCount(temp + 1) }} style={{ marginTop: "20px", marginBottom: "20px" }}>click this</button>
            <Router>
                <ul>
                    <li><Link to="/"> Test center </Link></li> <li><Link to="/group"> Component center </Link></li> </ul> <Route path="/" exact component={Interface} />
                <Route path="/group"  component={Group} />
            </Router>
        </div>
    );
}
export default Example2;
Copy the code
3) Use the useEffect to implement basic uninstallation
import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

function Interface{// add useEffect(() => {console.log(' Welcome Interface!!! `);return ()=>{
            console.log("ByeBye Interface")}})return<h2> Interface test </h2>}function Group() {// add useEffect(() => {console.log(' Welcome Group!! `);return ()=>{
            console.log("ByeBye Group")}})return<h2> Component test </h2>}Copy the code

At this point you’ll notice that even though you’ve mentally fulfilled the meaning of unload, when you click on the Click button you’ll still find ByeBye… In fact, every time the state changes, useEffect is bound. So how do you implement something like componentWillUnmount?

4) Use the second parameter of useEffect to realize uninstallation

In the useEffect function, the first parameter is a function, and the second parameter is an array. The array stores the state value, which is unbound only when the state value changes. If it is an empty array, it is unbound only when the component changes. The code is as follows:

function Interface() { useEffect(() => { console.log(`Welcome Interface!!! `);return ()=>{
            console.log("ByeBye Interface"}},[]) // Focus on this linereturn<h2> Interface test </h2>}function Group() { useEffect(() => { console.log(`Welcome Group!!! `);return ()=>{
            console.log("ByeBye Group"}},[]) // Focus on this linereturn<h2> Component test </h2>}Copy the code

5.useContext

Used to transfer values between parent and child components, equivalent to props. First generate a Context using createContext:

const TempContext  = createContext();
Copy the code

But before we do that, we need to introduce:

import React, { useState, useEffect, useContext, createContext } from 'React';
Copy the code

Then, if you want to pass temp to a child component, define a Provider that provides it:

Provider value={temp}>// The value of the value property is stored in the public area of the context.Copy the code

In Child component child.js:

function Child() {let temp = useContext(TempContext);
    return(<div> to child component: {temp}</div>)}Copy the code

The renderings are as follows:

import React, { useState, useEffect, createContext, useContext } from 'react';

const TempContext = createContext();

function Child() {let temp = useContext(TempContext);
    return(<div> to child component: {temp}</div>)}function Example3() {
    const [temp, setCount] = useState(0);
    useEffect(() => {
        console.log(`useEffect=>You clicked ${temp} times`);
    })
    return (
        <div>
            <div>
                clickResult is {temp}
            </div>
            <button onClick={() => { setCount(temp + 1) }} style={{ marginTop: "20px", marginBottom: "20px" }}>click this</button>
            <TempContext.Provider value ={temp}>
                <Child />
            </TempContext.Provider>
            
        </div>
    );
}


export default Example3;
Copy the code

6.useReducer

Reducer arises from Redux, but is irrelevant. Reducer is a function and can be defined as follows:

function tempReducer (state,action){
    switch(action.type){
        case 'add':
            return state+1
        case 'sub':
            return state-1
        default:
            return state
    }
}
Copy the code

The above code is to achieve a basic Reducer. Let’s look at the useReducer in detail

import React, { useState, useEffect, createContext, useContext, useReducer } from 'react';

function Example4() {
    // const [temp] = useState(0);
    const [temp, dispatch] = useReducer((state, action) => {
        switch (action) {
            case 'add':
                return state + 1
            case 'sub':
                return state - 1
            default:
                returnState}},0) // The second argument is the initial value of state,return (
        <div>
            <div>
                clickResult is {temp}
            </div>
            <button onClick={() => { dispatch('add') }} style={{ marginTop: "20px", marginBottom: "20px" }}>click add</button>
            <button onClick={() => { dispatch('sub') }} style={{ marginTop: "20px", marginBottom: "20px" }}>click sub</button>
            

        </div>
    );
}


export default Example4;
Copy the code

The useReducer method has two parameters, the second parameter is the default value, and its return value has two, one is the status, the other is the dispatcher. Dispatch is a dispatcher, which in Redux is usually written like this:

dispatch(
    type:xxx,
    value:xxx
)
Copy the code

The renderings are as follows:

7. UseContext and useReducer implement Redux

UseContext: enables access to the global status. This is consistent with Redux state globalization and unified management. UseReducer: Updates the status of complex logic through action transmission, mainly to achieve the Reducer part in Redux to achieve the feasibility of service logic. To illustrate, define two buttons to control font color, with buttons in one component and text in another. Effect:

Step 1: Write the shared state:

Start by defining a total component: example6.js

import React, { useReducer } from 'react';
import Example5 from './Example5';
import Examplebtn1 from './Examplebtn1';
import { Color } from './Change'; // Introduce the Color componentfunction Example6() {return(<div> <Color> //Color component used to share state <Example5 /> <Examplebtn1 /> </Color> </div>)}Copy the code

Write the shared component Color:

import React, { createContext } from 'react'; // Create a Context firstexportconst ColorContext = createContext(); // create the shared state of Color againexport const color = props=>{
    return(
        <ColorContext.Provider value={{color:"black"}}> // set the default value black {props. Children} // here, props. Children are each component in Color </ colorcontext.provider >)}Copy the code

Finally, write example5.js

import React, { useContext } from 'react';
import { ColorContext } from './Change';

function Example5() {let {color} = useContext(ColorContext);
    return<div style={{color:color}}> color: {color}</div>export default Example5
Copy the code
Step 2: Write a Usereducer to update the status value

Define two parameters in the Reducer: change.js

import React, { createContext, useReducer } from 'react';

export const UPDAT_COLOR = "UPDAT_COLOR";

const  reducer = (state, action) =>{
    switch(action.type){
        case UPDATE_COLOR:
            return action.color
        default:
            return state
    }
}

export const Color = props=>{
    const  [color,dispatch] = useReducer(reducer,'blue')
    return(
        <ColorContext.Provider value={{color:color,dispatch}} >
            {props.children}
        </ColorContext.Provider>
    )
}
Copy the code

Write the button component Examplebtn1

import React, { useContext }  from 'react';
import { ColorContext, UPDATE_COLOR } from './Change'

function Examplebtn1(){
    const {dispatch} = useContext(ColorContext)
    return(
        <div>
            <button style={{marginTop:"20px",marginRight:"20px"}} onClick={()=>{dispatch({type:UPDATE_COLOR,color:"red"</button> <button onClick={()=>{dispatch({)type:UPDATE_COLOR,color:"yellow"</button> </div>)}export default Examplebtn1
Copy the code

See the code: github.com/gt3060/reac…