react useEffect 模拟生命周期
import React,{ useState,useEffect} from "react"export default function FunComp(){const [ count, setCount ] = useState(0)const [ width, setWidth ] = useState(document.body.clientWidth)const onChange =
·
import React,{ useState,useEffect } from "react"
export default function FunComp(){
const [ count, setCount ] = useState(0)
const [ width, setWidth ] = useState(document.body.clientWidth)
const onChange = () => {
setWidth(document.body.clientWidth)
}
useEffect(() => {
// 相当于 componentDidMount
window.addEventListener('resize', onChange, false)
return () => {
console.log('销毁了')
// 相当于 componentWillUnmount
window.removeEventListener('resize', onChange, false)
}
}, [])
useEffect(() => {
document.title = count
// 相当于 componentDidUpdate
})
useEffect(() => {
console.log(`count change: count is ${count}`)
}, [ count ])
return (
<div>
页面名称: { count }
页面宽度: { width }
<button onClick={() => { setCount(count + 1)}}>点我</button>
</div>
)
}
更多推荐
已为社区贡献4条内容
所有评论(0)