useEffect:dom完成渲染后执行
- 不传参数,每次都会执行
传空的依赖[]
,只会执行一次
有依赖,依赖项变化会执行
useEffect实现动画效果
import { useEffect, useRef, useState } from "react"
const App = () => {
const [, setCount] = useState({})
const refDiv = useRef()
useEffect(() => {
console.log('执行useEffect')
setTimeout(() => {
refDiv.current.style.transform = 'translateX(150px)'
refDiv.current.style.transition = 'all .9s'
}, 1000)
// 清理函数 要显示返回的动画,上面的函数应延迟一段执行
// 否则太快回到150px位置,看不到效果
return () => {
console.log('执行清理函数')
refDiv.current.style.transform = 'translateX(0px)'
refDiv.current.style.transition = 'all .9s'
}
})
const styleObj = {
width: '50px',
height: '50px',
background: 'skyblue'
}
return (
<>
<div style={styleObj} ref={refDiv}></div>
<button onClick={() => setCount({})}>click</button>
</>
)
}
export default App
useLayoutEffect
- 和
componentDidMount
和componentDidUpdate
调用阶段一致
import { useEffect, useLayoutEffect, useRef, useState } from "react"
const App = () => {
const [, setCount] = useState({})
const refDiv = useRef()
useLayoutEffect(() => {
console.log('useLayoutEffect渲染前执行')
// 若不延迟 在useLayoutEffect看不到移动,而是初始就在150的位置
setTimeout(() => {
refDiv.current.style.transform = 'translateX(150px)'
refDiv.current.style.transition = 'all .9s'
}, 1000)
return () => {
console.log('执行清理函数')
refDiv.current.style.transform = 'translateX(0px)'
refDiv.current.style.transition = 'all .9s'
}
})
const styleObj = {
width: '50px',
height: '50px',
background: 'skyblue'
}
return (
<>
<div style={styleObj} ref={refDiv}></div>
<button onClick={() => setCount({})}>click</button>
</>
)
}
export default App
useDebugValue
- 用于在React开发者工具中显示自定义hook的标签
自定义hook
import { useEffect, useState } from 'react'
// 自定义hook
const useCount = params => {
const [count, setCount] = useState(0)
useEffect(() => {
document.title = `第${count}次点击`
})
return [count, setCount]
}
const Foo = () => {
const [count, setCount] = useCount(0)
useEffect(() => {
console.log('Foo useEffect')
})
return (
<>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>click</button>
</>
)
}
const App = () => {
return <Foo />
}
export default App