The usage of react hook is enough

Time:2022-5-13

1. Preface

1. I wrote a superficial article beforeHook first acquaintanceIntroduce hook
2. Summarize the commonly used hooks today
3. The whole is divided into two parts. One part is fromreactMy hook
4. Part isreact-reduxMy hook
5. Scaffold project is ready for construction


2. hook from ‘react’

import { useState, useEffect, useReducer } from 'react'

3. useState

As the name suggests, it is mainly used forstate, or forstatePackaging and splitting modules


3.1 grammar

    const [state, setstate] = useState(initialState)

Set initial value
Return the array, deconstruct the state and modify the function
State and modify function names can be changed by yourself


3.2 use

  let [num, setNum] = useState(0)

layout
Use modification

<h1>{num} </h1>
< button onclick = {() = > {setnum (Num + 1)}} > + modify num < / button >
< button onclick = {() = > {setnum (num - 1)}} > - modify num < / button >

Very simple counter demo


3.3 use a separate state module

0. Separate state is convenient for unified managementstate
1.state. JS content

const user = { 
     Test: 'test',
     userInfo:{
         name:'yzs',
         job:'web'
     }
}
export default  user

2. Use introduction

import myState from './state.js'
  1. Specific use

const [state, setState] = useState(myState)
  let { userInfo, test } = state

It is more silky to use with deconstruction assignment


3.4 render

<h1>Hook practice</h1>
            <h1>{userInfo.job}--{test}</h1>
            < div > < button onclick = {updatestate} > Modify < / button > < / div >
            <hr />

3.5 implementation of modified function

let updateState = () => {
        setState({
            ...state,
            Test: 'changed',
            userInfo: {
                ...state.userInfo,
                Job: 'front end Practitioner',
                age: 31
            }
        })
    }

1. Generally speaking, hook is not practicalthis
2. Clear data source
3. Easy to reuse
4. Pay attention to the modification method of variables of reference type


4. useEffect

We generally understand this as an alternative to the life cycle

// ****************DidMount+DidUpdate
    useEffect(()=>{
        console. Log ("called during initialization or update")
     })

//****************DidMount
    useEffect(() => {
        console. Log ('---------- initialization')
        return () => {
                //*****************WillUnMount
            console.log("cleanup")
        }
    }, [])
//*******************DidUpdate
    useEffect(() => {
        console. Log ("when the initialization or listening object changes")
    }, [num])

5. useReducer

1. This is notreact-reduxHook inside
2. Actually, thisreducerRepresents an idea, modify the encapsulation of functions and form independent modules
3. So it doesn’t mean it has to bereduxInsidereducerOf coursereduxofreducerIt can also be used


5.1 reducer preparation

1. Since the name isreducerPrepare one first
2. It is still a simple counter as the introduction to carry out
3. This can also be a separate module / file

let defaultState = {
        count: 66666,
        person: {
            name: 'yzs',
            City: 'Zhengzhou'
        }
    }
//***********This action is directly deconstructed and assigned an initial value
    const reducer = (state, { type, payload=10 }) => {
        switch (type) {
            case 'increment':
                return {
                    ...state,
                    count: state.count + payload
                }
            case 'decrement':
                return {
                    ...state,
                    count: state.count - payload
                }
            case 'PERSON_UPDATE': {
                console. Log ('object modification: ', payload)
                return {
                    ...state,
                    person: {
                        ...state.person,
                        ...payload
                    }
                }
            }
            default:
                return state
        }
    }

1. ParametersstateThe initial value of can also be a single variable or another initialization module
2. The second parameter is the load. I directly deconstruct it here and assign the initial value. This is just to explain the modification method of basic type and reference type, so it is put together. Otherwise, the initial value should be handled separately
3.stateThe modification method of cannot be modified directly


5.2 use

1. Importreducermodular
2. Plug inuseReducerThis grammar

        const [state, dispatch] = useReducer(reducer, initialState, init)

3. Parameter requirementsreducerThat’s why we prepared in the first stepreducer
4. Core code

   // ******************* useReducer
    const [pageState, dispatch] = useReducer(reducer, defaultState)
    let { count, person } = pageState

1. The second parameter here is the initial value, which is optional
2. It will be coveredreducerInsidestateParameter initial value
3. I directly report the resultsstateDirectly deconstructed


5.3 use of state and dispatch

<hr />
            <h1>useReducer</h1>
            <h1>
                < button onclick = {() = > {dispatch ({type: 'increment'})} > + modify < / button >
                {count}
                < button onclick = {() = > {dispatch ({type: 'increment', payload: 100})} > - modify < / button >
            </h1>
            <h1>{person.city}
            < button onclick = {updateobj} > - modify < / button ></h1>

1. This andvuexAuxiliary functions are similar in usage
2.typeValue sumreducerbring into correspondence with
3. Parameter keypayloadandreducerThe parameters inside are consistent


5.4 difference between usereducer and Redux

1.useReducerIt’s usestatereplaceScheme, mainly used forState complexChanging scene
2. Usereducer yesSingle componentProps is also required for state management and component communication
3. Redux yesoverall situationState management, multi component sharing data


5.5 reactHook summary

1. Understandvue3Can be combinedvue3Combined API to understand
2. Usestate is responsible for data correlation, clear source and convenient reuse
3. Unified processing of usereducer data logic


useRef

Get DOM

use

  let { useState, useRef,useEffect } = React
 const myref1 = useRef("yzs")
 const myref2 = useRef("yzs")

hook

  let  testR = null            
// ********didMount didUpdate
            useEffect(() => {
                testR.style.color = "red"
                console.log("DOM:", testR.innerHTML);
                myref1.current.style = "color: orange";
                console.log(myref1,myref2);
            })

layout

< H1 ref = {El = > testr = El} > test</h1>
< p ref = {myref1} > demo useref</p>
 < div ref = {myref2} > I am a div < / div >

6. hook from react-redux

6.1 preparation

1. This isreduxdependenthook, so you need to preparereduxBasic configuration of
2. Don’t talk about installation. Install it yourselfnpm i react-redux -S
Src. Store structure
4. Of reducer and Article 5useReduerJust use one in the explanation
5.store/index. JS integrationreducer


6.2 store

Unique store

import reducer from '../pages/search/store'
//Undivided writing
//Import
import {createStore,combineReducers} from 'redux'

//Create store
const rootReducer = combineReducers({
    hookPageYzs:reducer,
})

let store = createStore(rootReducer)
export default store

1. Pay attention to the root herereducerConfigured withhookPageYzs


7.useSelector

import { useSelector, useDispatch } from 'react-redux'

7.1 useselector logic

This hook is used to use the state in react redux

const hookpageAge = useSelector((state) => {
        console.log("hook------------------state", state)
        return state.hookPageYzs
    })
    console.log("useSelector----------HookPage", hookpageAge)

1. If you don’t understand, print or read the logic
2.hookPageYzsIt is configured in the root store


7.2 data display

<div> redux-hook----{hookpageAge.count}  </div>
 <h1>{hookpageAge.person.name}</h1>

For the general reducer, see 5.1 reducer preparation above

let defaultState = {
        count: 66666,
        person: {
            name: 'yzs',
            City: 'Zhengzhou'
        }
    }

8. useDispatch

 //************************  useDispatch
    const dispatch= useDispatch()

1. Be careful not to repeat the name
2. UseuseReducerWhen deconstructed, the default is also calleddispatch
3. I don’t use this in the same interface, so it won’t be repeated


8.1 basic types

<hr />
            <h1> react-redux -hook</h1>
          <div> redux-hook----{hookpageAge.count}  </div>
            <h1>
                < button onclick = {() = > {add (10000)} > + add < / button >
                <button onClick={() => {
                    dispatch({
                        type: 'decrement'
                    })
                }}>-Reduce < / button ></h1>
            <hr />

8.2 basic type modification

 let add = (payload) => {
        dispatch({
            type: 'increment',
            payload
        })
    }

1. This function declares the arrow function separately. When binding events, you need to use the arrow function
2. For direct modification without binding, it also needs to be filled in the arrow function of the event, because parameters need to be passed


8.3 reference type

<h1>{hookpageAge.person.name}</h1>
            <h1>Reference type modification
                < button onclick = {updateobj} > Modify < / button >
            </h1>

8.4 modification

let updateObj =()=>{
        dispatch({
            type:'PERSON_UPDATE',
            Payload: {Name: 'misty rain', age: 18}
        })
    }

9. Persistence

If you want to combine persistence, just read the previous articleRedux persistence


reference material

react-hook
Hook first acquaintance
Redux persistence


Initial heart

All my articles are just based on introduction and preliminary understanding; Is to sort out their own knowledge system;
It’s a great honor if you can help someone who is destined for youtribeThe rise of;
Encourage each other