关注公众号,更多精彩内容等着你
Hook 出现解决了什么 ?
什么时候使用 Hook ?
React
内置的 Hook
useState
状态管理
useState
定义 / 使用
完整栗子
import {useState} from 'react';
export default () => {
const [data, setData] = useState('微信公众号: 前端自学社区')
return (
<div>
<h1>{data}</h1>
{/* 更新 state */}
<button onClick={()=>{setData('微信公众号: 前端自学社区 666')}}></button>
</div>
)
}
useEffect
生命周期管理
定义
无需清除Effect
使用
❞ useEffect(() => {
//默认会执行
// 这块相当于 class 组件 生命周期的
//compoentDidmount compoentDidUpdate
}, [])
清除Effect
使用
2. 为什么 要在 Effect
中返回一个函数 ?
❞ useEffect(()=>{
return () => {
console.log('组件卸载时执行')
}
})
监听 state
变化
useEffect(() => {
// 监听num,count 状态变化
// 不监听时为空 [] , 或者不写
}, [num, count])
完整栗子
import { useState, useEffect } from 'react';
export default () => {
const [num, setNum] = useState(0)
const [count, setCount] = useState(1)
useEffect(() => {
//默认会执行
// 这块相当于 class 组件 生命周期的 compoentDidmount compoentDidUpdate
console.log(`num: ${num}`)
console.log(`count: ${count}`)
// 组件在卸载时,将会执行 return 中内容
return () => {
// 相当于 class 组件生命周期的 componentWillUnMount
console.log('测试')
}
}, [num])
return (
<div>
<h1>{num}</h1>
<button onClick={() => { setNum(num + 1) }}> 更新Num</button>
<hr />
<h1>{count}</h1>
<button onClick={() => { setCount(count + 1) }}> 更新Count</button>
</div>
)
}
useRef
什么是 useRef
?
栗子
import {useRef} from 'react';
export default () => {
const inputRef = useRef({value:0})
return (
<div>
<h1>测试</h1>
<input type="text" ref={inputRef} />
<button onClick={()=>{console.log(inputRef.current.value)}}>获取input 值</button>
<button onClick={()=>{inputRef.current.focus()}}>获取input 焦点</button>
</div>
)
}
useContext
状态数据共享
Context
解决了什么
什么是 Context
创建 Context
import React from 'react';
export const MyContext = React.createContext();
使用 Context
// Context.js
import React from 'react';
export const MyContext = React.createContext();
import { useContext } from 'react';
import {MyContext} from '../Context/index'
const result = {
code:200,
title:'添加数据成功'
}
const Son = () => {
const res = useContext(MyContext)
return (
<>
<div>
<h1>{res.code}</h1>
<hr/>
<h2>{res.title}</h2>
</div>
</>
)
}
export default () => {
return (
<MyContext.Provider value={result}>
<div>
<h1>前端自学社区</h1>
<Son/>
</div>
</MyContext.Provider>
)
}
useMemo
提升性能优化
定义
栗子
import { useState, useMemo} from 'react';
export default () => {
const [count, setCount] = useState(0)
const [num, setNum] = useState(0)
const newValue = useMemo(()=>{
console.log(`count 值为${count}`)
console.log(`num 值为 ${num}`)
return count+num
},[count])
return(
<div>
<h1>{count}</h1>
<button onClick={()=>{setCount(count+1)}}>count + 1</button>
<hr/>
<h1>{num}</h1>
<button onClick={()=>{setNum(num+1)}}>Num + 1</button>
<hr/>
<h2>{newValue}</h2>
</div>
)
}
解析栗子
useCallback
提升性能优化
定义
使用
import { useState, useCallback} from 'react';
export default () => {
const [count, setCount] = useState(0)
const [num, setNum] = useState(0)
const newValue = useCallback(()=>{
console.log(`count 值为${count}`)
console.log(`num 值为 ${num}`)
return count+num
},[count])
return(
<div>
<h1>{count}</h1>
<button onClick={()=>{setCount(count+1)}}>count + 1</button>
<hr/>
<h1>{num}</h1>
<button onClick={()=>{setNum(num+1)}}>Num + 1</button>
<hr/>
{/* 调用useCallback 返回的值 */}
<h2>{newValue()}</h2>
</div>
)
}
小结
大家对 useMemo
和 useCallback
有何看法,欢迎在下方评论或者加我讨论。
❞ useImperativeHandle
定义
格式: useImperativeHandle(ref,()=>{},[])
import {useState,useImperativeHandle, forwardRef,useRef} from 'react';
const Son = forwardRef( (props,ref) => {
const inputRef = useRef(0)
const domRef = useRef()
const [state, setState] = useState('等待')
useImperativeHandle(ref,()=>({
focus:() => {inputRef.current.focus()},
domRef
}))
return (
<div>
<h1>{state}</h1>
<hr/>
<input type="text" ref={inputRef}/>
<h2 ref={domRef}>测试---------useImperativeHandle</h2>
</div>
)
})
export default () => {
const refFather = useRef(0)
return (
<div>
<h1>父组件</h1>
<Son ref={refFather} />
<button onClick={()=>{refFather.current.focus()}}>获取子组件实例------获取input焦点</button>
<button onClick={()=>{console.log(refFather.current.domRef.current.innerHTML)}}>获取子组件实例------获取h2 Dom</button>
</div>
)
}
useReducer
定义
使用Reducer
实现一个加减器
import {useReducer} from 'react';
export default () => {
const [state, dispatch] = useReducer((state,action)=> {
switch (action.type){
case 'addNum':
return {
num:state.num+1
}
case 'subtractNum':
return {
num:state.num-1
}
}
},{
num:0
})
return (
<div>
<h2>{state.num}</h2>
<button onClick={()=>{dispatch({type:'addNum'})}}> 增加num</button>
<button onClick={()=>{dispatch({type:'subtractNum'})}}> 增加num</button>
</div>
)
}
本文分享自微信公众号 - 前端自学社区(gh_ce69e7dba7b5)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。