React扩展之函数Hooks

2021-12-14  本文已影响0人  硅谷干货

初始化项目

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import {BrowserRouter} from 'react-router-dom'

ReactDOM.render(
    <BrowserRouter>
        <App/>
    </BrowserRouter>,
    document.getElementById('root'))

setState

import React, { Component } from 'react'

export default class Demo extends Component {

    state = {count:0}

    add = ()=>{
        //对象式的setState
        /* //1.获取原来的count值
        const {count} = this.state
        //2.更新状态
        this.setState({count:count+1},()=>{
            console.log(this.state.count);
        })
        //console.log('12行的输出',this.state.count); //0 */

        //函数式的setState
        this.setState( state => ({count:state.count+1}))
    }

    render() {
        return (
            <div>
                <h1>当前求和为:{this.state.count}</h1>
                <button onClick={this.add}>点我+1</button>
            </div>
        )
    }
}

useEffect

import React from 'react'
import ReactDOM from 'react-dom'

//类式组件
/* class Demo extends React.Component {

    state = {count:0}

    myRef = React.createRef()

    add = ()=>{
        this.setState(state => ({count:state.count+1}))
    }

    unmount = ()=>{
        ReactDOM.unmountComponentAtNode(document.getElementById('root'))
    }

    show = ()=>{
        alert(this.myRef.current.value)
    }

    componentDidMount(){
        this.timer = setInterval(()=>{
            this.setState( state => ({count:state.count+1}))
        },1000)
    }

    componentWillUnmount(){
        clearInterval(this.timer)
    }

    render() {
        return (
            <div>
                <input type="text" ref={this.myRef}/>
                <h2>当前求和为{this.state.count}</h2>
                <button onClick={this.add}>点我+1</button>
                <button onClick={this.unmount}>卸载组件</button>
                <button onClick={this.show}>点击提示数据</button>
            </div>
        )
    }
} */

function Demo(){
    //console.log('Demo');

    const [count,setCount] = React.useState(0)
    const myRef = React.useRef()

    React.useEffect(()=>{
        let timer = setInterval(()=>{
            setCount(count => count+1 )
        },1000)
        return ()=>{
            clearInterval(timer)
        }
    },[])

    //加的回调
    function add(){
        //setCount(count+1) //第一种写法
        setCount(count => count+1 )
    }

    //提示输入的回调
    function show(){
        alert(myRef.current.value)
    }

    //卸载组件的回调
    function unmount(){
        ReactDOM.unmountComponentAtNode(document.getElementById('root'))
    }

    return (
        <div>
            <input type="text" ref={myRef}/>
            <h2>当前求和为:{count}</h2>
            <button onClick={add}>点我+1</button>
            <button onClick={unmount}>卸载组件</button>
            <button onClick={show}>点我提示数据</button>
        </div>
    )
}

export default Demo

上一篇 下一篇

猜你喜欢

热点阅读