Hooks学习笔记之useEffect的进阶使用方式及参数解释:

完整代码:

演示地址

import React, { useState, useEffect} from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'

const Index = () => {
    useEffect(() => {
        console.log('useEffect=>This index page')
        return () => {
            console.log('You leave index page')
        }
    }, [])
    return <h2>Hi! This index</h2>
}

const List = () => {
    useEffect(() => {
        console.log('useEffect=>This list page')
        return () => {
            console.log('You leave list page')
        }
    }, [])
    return <h2>Hi! This list</h2>
}

const Test = () => {
    const [count, setCount] = useState(0)

    useEffect(() => {
        console.log(`useEffect=>You clocked ${count} times`)
        return() => {
            console.log('============')
        }
    }, [count])
    
    return (
        <div>
            <p>clicked:{ count }</p>
            <button onClick={() => {setCount(count + 1)}}>click</button>

            <Router>
                <ul>
                    <li><Link to="/">首页</Link></li>
                    <li><Link to="/list/">列表</Link></li>
                </ul>
                <Route path="/" exact component={Index} />
                <Route path="/list/" component={List} />
            </Router>

        </div>
    )
}
export default Test

参数解释

useEffect(() => {
    console.log(`useEffect=>You clocked ${count} times`) // 在渲染后调用
    return() => { // 类似销毁后调用
        console.log('============')
    }
}, [count]) // []中参数为绑定触发的参数、当count修改时才会触发,不写则将',[]'删除。