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> ) }
.