zoukankan      html  css  js  c++  java
  • React的Hook函数之React.useState()、React.useEffect()

    如果只使用类式组件,满足以下功能很容易:

    • 在组件挂载时,启动定时器,每隔1s加1;
    • 组件将要卸载时,停止定时器
    • 点击按钮卸载组件
      具体实现:
    import React, { Component } from 'react'
    import ReactDOM from 'react-dom'
    
    export default class App extends Component {
        state = {
            count:0
        }
    
        componentDidMount(){
            this.timer = setInterval(() => {
                this.setState(state=>({count:state.count+1}))
            }, 1000);
        }
    
        componentWillUnmount(){
            clearInterval(this.timer)
        }
    
        unmount = ()=>{
            ReactDOM.unmountComponentAtNode(document.getElementById('root'))
        }
    
        render() {
            return (
                <div>
                    <h2>当前求和为:{this.state.count}</h2>
                    <button onClick={this.unmount}>点我卸载组件</button>
                </div>
            )
        }
    }
    
    

    如果使用函数式组件呢,由于函数中没有this实例,无法直接使用state和生命周期钩子和ref等,就得用React.useState()和React.useEffect()

    具体实现:

    import React from 'react'
    import ReactDOM from 'react-dom'
    
    export default function App(){
    
        // 数组第一个参数为state要保存的值,第二个为操作state的方法,useState()的参数为state的初始值
        const [count, setCount] = React.useState(0)
    
        //第一个参数为生命周期钩子函数,第二个参数为要检测的状态列表,如果状态发生改变则调用钩子函数
        React.useEffect(()=>{
            const timer = setInterval(() => {
                setCount(count=>count+1)
            }, 1000);
    
            return ()=>{//这个返回的函数会在组件将要卸载时调用,相当于componentWillUnmount()
                clearInterval(timer)
            }
        },[])//空数组表示不检测任何状态,此时相当于componentDidMount(),否则还相当于componentDidUpdate()
    
        function unmount(){
            ReactDOM.unmountComponentAtNode(document.getElementById('root'))
        }
    
        return (
            <div>
                <h2>当前求和为:{count}</h2>
                <button onClick={unmount}>点我卸载组件</button>
            </div>  
        )
    }
    
  • 相关阅读:
    Fatal error compiling: invalid target release: 11 -> [Help 1]
    java -jar 设置日志位置
    wordpress 添加 显示磁盘剩余空间百分比的插件
    记录我个人对Telegram的了解
    Ubuntu 18.04 切换使用Python3
    基于 CI 1.7.x 的 项目使用新版本CI的文件缓存类库
    使用sqlyog工具同步两个相同结构的数据库之间的数据
    了解GTIN小记
    华为手机设置桌面图标角标提醒的实现
    Quill编辑器IOS下无法获取焦点的解决方法
  • 原文地址:https://www.cnblogs.com/pangqianjin/p/14786323.html
Copyright © 2011-2022 走看看