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