zoukankan      html  css  js  c++  java
  • 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>
      )
    }
    

    .

  • 相关阅读:
    day 011总结
    day 010 总结
    day 10作业
    day 009总结
    day 008总结
    wireshark 解密tls消息
    js基础 数组slice
    js基础 数组splice
    js基础 Array.from
    js基础 Array.of
  • 原文地址:https://www.cnblogs.com/crazycode2/p/12640125.html
Copyright © 2011-2022 走看看