React.useEffect模拟生命周期

  • 模拟componentDidMount

      第二个参数为空数组,可以模拟compomentDidMount

useEffect(()=>{console.log('第一次渲染时调用')},[])
  • 模拟componentDidUpdate

     没有第二个参数代表监听所有属性的更新

useEffect(()=>{console.log('任意属性该改变')}) 

  监听多个属性的变化需要将属性作为数组传入第二个参数。

useEffect(()=>{console.log('n变了')},[n,m]) 
  • 模拟componentWillUnmount

    通常,组件卸载时需要清除 effect 创建的诸如订阅或计时器 ID 等资源

useEffect(()=>{
    const timer = setTimeout(()=>{
        ...
    },1000)
    return()=>{
        console.log('组件销毁了')
        clearTimerout(timer)
    }
})

 

posted @ 2022-07-06 16:00  bug制造者~~  阅读(777)  评论(0)    收藏  举报