useEffect 模拟 react 生命周期


1.代码

function App () {
  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 () => {
      // 相当于 componentWillUnmount
      window.removeEventListener('resize', onChange, false)
    }
  }, [])

  useEffect(() => {
    // 相当于 componentDidUpdate
    document.title = count
  })

  useEffect(() => {
    console.log(`count change: count is ${count}`)
  }, [ count ])

  return (
    <div>
      页面名称: { count } 
      页面宽度: { width }
      <button onClick={() => { setCount(count + 1)}}>点我</button>
    </div>
  )
}

.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM