HOOKS function extension

1. What is HOOK

The function component built in the system in React component is a new feature in version 16.8. It is used to support the addition of specially modified data and life cycle management of components during functional component development

Core: service functional component
Function: status management mode
Function 2: life cycle
Scenario: due to the characteristics of functional component declaration syntax, the amount of code should be due to class components. For some simple component development, it has natural advantages for using lightweight components in data management and life cycle. It should be noted that this technology is a new feature in framework development, After the technology is used and mature in most projects, it may be adopted in its own projects

2.State Hook

Support function components in State Hook can contain their own state data
In the original functional component, the update operation of data in variables can be controlled through events, but:

The update of variable data controlled by the event function will not be fed back to the page component. The current variable data does not receive the component state management, so the change of data will not cause the update of component state
Macroscopically speaking, component state management is component data management
In detail, the state description is controllable and predictable data, and the data update operation can be monitored and bi-directional synchronized by the component

let counter= 0
function increase() {
    counter ++
    console.log(counter)
}
function decrease() {
    counter --
    console.log(counter);
}
export default function FunComp01 () {
    return <div>
        <h1>Functional components: state hook use</h1>
        <h3>Counter:{counter}</h3>
        <button onClick={increase}>increase</button>
        <button onClick={decrease}>reduce</button>
    </div>
}

Status data management

import {useState} from 'react'
   export default function FunComp() {
    // Add a status data to the functional component
    //useState is a function that internally describes the default value of state data
    // The first data is the variable that holds the number of states
    // The second data: is a function that operates on data
    let [myCounter,setCounter] = useState(0)
    function increase() {
        setCounter(++myCounter)
    }
    function decrease() {
        setCounter(--myCounter)
    }
    return <div>
        <h3>Counter:{myCounter}</h3>
       <button onClick={increase}>increase</button>
        <button onClick={decrease}>reduce</button>
    </div>
}

3.Effect Hook

Description: the react core package supports functional components with their own life cycle
Note: effect hook provides life cycle management and extends the functions of functional components
Scenario: functional components can be allowed to complete the suggested functions that can only be completed by some types of components

import {useState,useEffect} from 'react'
export default function FunComp01() {
	//Add a status data to the functional component
	//useState is a function: the default value of state data is described inside the function
	//The return value of useState contains two data
	//The first data is the variable that holds the status data
	//The second data: is a function that operates on data 
	let [myCounter,setCounter] = useState(0)
	let [msg,setMsg] = useState('Message data')
	...
	function setMessage() {
		setMsg('New message data')
	}
	//The useEffect() function itself accepts a function parameter and adds the corresponding life cycle
	useEffect(()=>{
		//The loading of componentDidMount() is simulated
		// Simulated componentDidUpdate() update
		// Uninstallation of componentWillUnmount() is simulated
		console.log('useEffect Function executed')
		return ()=> {
		   console.log('useEffect The function component is about to be uninstalled')
		} 
	})
	useEffect(()=>{
		//The useEffect function can be defined and executed multiple times
		console.log('useEffect2 Function executed')
	})
	useEffect(()=>{
		//useEffect function, which can listen to one or more variables, and execute the function when calling variable update
		console.log('useEffect mycounter Function executed')
	},[myCounter])
	...
		<h3>Message data</h3>
		<button onClick={setMessage}>update message</button>
	...
}

4.Reducer Hook

Description: react is a state management mode added to functional components, which can update complex state data

import {useReducer} from 'react'
export default function Fucomp02{
	cosnt goodsList = [
		{id:1,name:'Apple'},
		{id:2,name:'Samsung'}
	]
	function goodsReducer(state=goodsList,action) {
		switch(action.type){
		  case 'add':
                break;
            case 'edit':
                break;
            case 'del':
                break;
            default: 
                return goodsList
		}
	}
	let [state,dispatch] = useReducer(goodsRedcer,goodsList) {
	return <div>
		<h3>Functional components: useReducer application</h3>
		<ul>
			{
				state.map((goods,index)=>{
					return <li key={index}>{goods.name}</li>
				})
			}
		</ul>
</div>
}

The data update operation simulates the data status update method in reudx, and updates the data through actionCreators created by actionType

import {useState,useReducer} from 'react'
export default function FunComp02() {
	const goodsList = [{id:1,name:'Apple'},
		{id:2,name:'Samsung'}]
	let [name,setName] = useState('')
	let [cid,setId]=useState('')
	function goodsReducer(state=goodsList,action){
		switch(action.type) {
			case 'add': 
				let id = state.length > 0 ?state[0].id +1 : 1
				return [{id,name:action.data},...state]
			case 'edit':
				let index = state.findIndex(goods=>goods.id === action.data.id)
				state[index].name = action.data.name
				return state
			case 'del':
				return state.filter(goods=>goods.id!==action.data)
			default:
				return goodsList
		}
	}
	let [state,dispatch] = useReducer(goodsReducer,goodsList)
	function submitGood(e) {
		if(e.keyCode === 13) {
			console.log('Form data submission')
			if(cid!=='') {
				dispatch({type:'edit',data:{id:cid,name}})
			}else {
				dispatch({type:'add',data:name})
			}
			setId('')
			setName('')
		}
	}
	function deleteGoods(goods){
		disptch({type:'del',data:goods.id})
	}
	function editGoods(goods){
		setId(goods.id)
		setName(goods.name)
	}
	return <div>
		<h3>Functional components: useReducer application</h3>
        <input type="text" value={name}
            onChange={e=>setName(e.target.value)}
            onKeyUp={e=>submitGoods(e)}/>
        <ul>
           {
               state.map((goods, index) => {
                   return <li key={index}>{goods.name}
                        <button onClick={()=>deleteGoods(goods)}>delete</button>
                        <button onClick={ () => editGoods(goods)}>edit</button>
                    </li>
               })
           }
        </ul>
	</div>
}

Keywords: Javascript Front-end React

Added by blen on Wed, 15 Dec 2021 10:56:12 +0200