Hooks学习笔记之useEffect的使用方式:

1、基础使用方法:

(1)、代替缩短原先的生命周期函数

原先生命周期函数:

import React, { Component } from 'react'

export default class Test extends Component {
    state = {
        count: 0
    }

    componentDidMount() {
        console.log(`componentDidMount=>You clocked ${this.state.count} times`)
    }

    componentDidUpdate() {
        console.log(`componentDidUpdate=>You clocked ${this.state.count} times`)
    }


    render() {
        return (
            <div>
                <p>clicked:{ this.state.count }</p>
                <button onClick={this.addCount.bind(this)}>click</button>
            </div>
        )
    }

    addCount() {
        this.setState({count: this.state.count + 1});
    }
}

Hooks修改后:

import React, { useState, useEffect} from 'react'

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

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

useEffect的优点在于节省了原先的多种生命周期函数更加的便捷、缺点为在使用中为异步操作,不会实时影响视图操作。