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 fromreact
My hook
4. Part isreact-redux
My 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 for
state
, or forstate
Packaging 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 management
state
1.state. JS content
const user = {
Test: 'test',
userInfo:{
name:'yzs',
job:'web'
}
}
export default user
2. Use introduction
import myState from './state.js'
- 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 practical
this
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 not
react-redux
Hook inside
2. Actually, thisreducer
Represents an idea, modify the encapsulation of functions and form independent modules
3. So it doesn’t mean it has to beredux
Insidereducer
Of courseredux
ofreducer
It can also be used
5.1 reducer preparation
1. Since the name is
reducer
Prepare 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. Parameters
state
The 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.state
The modification method of cannot be modified directly
5.2 use
1. Import
reducer
modular
2. Plug inuseReducer
This grammar
const [state, dispatch] = useReducer(reducer, initialState, init)
3. Parameter requirements
reducer
That’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 coveredreducer
Insidestate
Parameter initial value
3. I directly report the resultsstate
Directly 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 and
vuex
Auxiliary functions are similar in usage
2.type
Value sumreducer
bring into correspondence with
3. Parameter keypayload
andreducer
The parameters inside are consistent
5.4 difference between usereducer and Redux
1.
useReducer
It’s usestatereplace
Scheme, mainly used forState complex
Changing scene
2. Usereducer yesSingle component
Props is also required for state management and component communication
3. Redux yesoverall situation
State management, multi component sharing data
5.5 react
Hook summary
1. Understand
vue3
Can be combinedvue3
Combined 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 is
redux
dependenthook
, so you need to prepareredux
Basic configuration of
2. Don’t talk about installation. Install it yourselfnpm i react-redux -S
Src. Store structure
4. Of reducer and Article 5useReduer
Just 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 here
reducer
Configured 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.hookPageYzs
It 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. UseuseReducer
When 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