Skip to content

useState

使用 useState 代替 state 声明值。

import React, {useState} from 'react'

    function UserStateExample() {
        const [count, setCount] = useState(0)

        return (
            <>
                <p>当前值为:{count}</p>
                <button onClick={()=>setState(count+1)}> 
                    clike me
                </button>
            </p>
        )
    }

    export example UserStateExample
import React, {useState} from 'react'

    function UserStateExample() {
        const [count, setCount] = useState(0)

        return (
            <>
                <p>当前值为:{count}</p>
                <button onClick={()=>setState(count+1)}> 
                    clike me
                </button>
            </p>
        )
    }

    export example UserStateExample

useEffect

class 组件中使用生命周期函数做些事情(如:接口请求数据)。然而在 ReactHooks 中也可以用 useEffect 做到。

可以代替 class 组件生命周期函数 componentWillMountcomponentDidMount

如下:

import React, {useEffect} from 'react'

    function HelloUseEffect() {
       const [count, setCount] = useState(0)

        useEffect(() => {
            console.log(`点击次数${count}次`)
        })


        return (
            <>
                <p>当前值为:{count}</p>
                <button onClick={()=>setState(count+1)}> 
                    clike me
                </button>
            </p>
        )
    }

    export default HelloUseEffect
import React, {useEffect} from 'react'

    function HelloUseEffect() {
       const [count, setCount] = useState(0)

        useEffect(() => {
            console.log(`点击次数${count}次`)
        })


        return (
            <>
                <p>当前值为:{count}</p>
                <button onClick={()=>setState(count+1)}> 
                    clike me
                </button>
            </p>
        )
    }

    export default HelloUseEffect

可以发现浏览器第一次渲染和组件更新都会执行该函数重新渲染数据。

userEffect 定义的函数不会阻止浏览器渲染更新视图,可以理解这些函数是异步的。

useEffect 实现 componentWillUnmount

import React, {useEffect} from 'react'

    function HelloUseEffect() {
       const [count, setCount] = useState(0)

        useEffect(() => {
            console.log(`点击次数${count}次`)

            return ()=>{ //解绑函数
                console.log(`==================`)
            }

        }, [count])


        return (
            <>
                <p>当前值为:{count}</p>
                <button onClick={()=>setState(count+1)}> 
                    clike me
                </button>
            </p>
        )
    }

    export default HelloUseEffect
import React, {useEffect} from 'react'

    function HelloUseEffect() {
       const [count, setCount] = useState(0)

        useEffect(() => {
            console.log(`点击次数${count}次`)

            return ()=>{ //解绑函数
                console.log(`==================`)
            }

        }, [count])


        return (
            <>
                <p>当前值为:{count}</p>
                <button onClick={()=>setState(count+1)}> 
                    clike me
                </button>
            </p>
        )
    }

    export default HelloUseEffect

useEffect 函数支持返回一个函数,即解绑函数;并加上第二个参数为空数组或者是定义的值。

只要有状态变化,解绑函数都会执行。

useContext

例子如下:

import React, {useState, createContext, useContext} from 'react'

    const countContext = createContext()

    function ChildExample() {
        let count 
        return (
            <>
                Child中的值为:{count}
            </>
        )
    }

    function UseContentExample() {
        const [count, setCount] = useState(0)

        return (
            <>
                <p>当前值为{count}</p>
                <button onClick={()=>setState(count)}>
                    click me
                </button>

                <countContext.Provider value={count}>
                    <ChildExample />
                </countContext.Provider>
            </p>
        )
    }


    export default UseContentExample
import React, {useState, createContext, useContext} from 'react'

    const countContext = createContext()

    function ChildExample() {
        let count 
        return (
            <>
                Child中的值为:{count}
            </>
        )
    }

    function UseContentExample() {
        const [count, setCount] = useState(0)

        return (
            <>
                <p>当前值为{count}</p>
                <button onClick={()=>setState(count)}>
                    click me
                </button>

                <countContext.Provider value={count}>
                    <ChildExample />
                </countContext.Provider>
            </p>
        )
    }


    export default UseContentExample

useContext 全局状态管理相当于模拟 Reduxstate

useReducer

例子如下:

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

    function UseReducerExample() {
        const [count, dispatch] = useReducer((state, action) => {
            switch(action) {
                case 'add':
                    return state + 1
                case 'sub':
                    return state - 1
                default:
                    return state
            }
        }, 0)

        return (
            <>
                <button onClick={()=>{dispatch('add')}}>
                    加数
                </button>
                <button onClick={()=>{dispatch('sub')}}>
                    减数
                </button>
            </>
        )
    }

    export default UseReducerExample;
import React,{useState, useReducer} from 'react'

    function UseReducerExample() {
        const [count, dispatch] = useReducer((state, action) => {
            switch(action) {
                case 'add':
                    return state + 1
                case 'sub':
                    return state - 1
                default:
                    return state
            }
        }, 0)

        return (
            <>
                <button onClick={()=>{dispatch('add')}}>
                    加数
                </button>
                <button onClick={()=>{dispatch('sub')}}>
                    减数
                </button>
            </>
        )
    }

    export default UseReducerExample;

action 更新逻辑,相当于 redux 中的 reducer

useMemo

useMemo 可以解决组件重复渲染。

import React, { useState, useMemo } from 'react';

    function UseMemoExample() {
        const [xiaohong, setXiaohong] = useState('xiaohong')
        const [zhiling, setZhiling] = useState('zhiling')
        return (
            <>
                <button 
                    onClick={()=>{setXiaohong(new Date().getTime())}}>
                        小红
                </button>
                <button 
                    onClick={()=>{setZhiling(new Date().getTime()+'志玲来了')}}>
                        志玲
                </button>
                <ChildComponent name={xiaohong}>{ zhiling }</ChildComponent>
            </>
        )
    }

    function ChildComponent({name, children}) {
        function changeXiaohong() {
            console.log(`xiaohong来了`);
            return name+`,xiaohong来了`
        }

        //const actionXiaohong = changeXiaohong(name)

        const actionXiaohong = useMemo(()=>changeXiaohong(name), [name])

        return (
            <>
                <div>{ actionXiaohong }</div>
                <div>{ children }</div>
            </>
        )
    }

    export default UseMemoExample
import React, { useState, useMemo } from 'react';

    function UseMemoExample() {
        const [xiaohong, setXiaohong] = useState('xiaohong')
        const [zhiling, setZhiling] = useState('zhiling')
        return (
            <>
                <button 
                    onClick={()=>{setXiaohong(new Date().getTime())}}>
                        小红
                </button>
                <button 
                    onClick={()=>{setZhiling(new Date().getTime()+'志玲来了')}}>
                        志玲
                </button>
                <ChildComponent name={xiaohong}>{ zhiling }</ChildComponent>
            </>
        )
    }

    function ChildComponent({name, children}) {
        function changeXiaohong() {
            console.log(`xiaohong来了`);
            return name+`,xiaohong来了`
        }

        //const actionXiaohong = changeXiaohong(name)

        const actionXiaohong = useMemo(()=>changeXiaohong(name), [name])

        return (
            <>
                <div>{ actionXiaohong }</div>
                <div>{ children }</div>
            </>
        )
    }

    export default UseMemoExample

useRef

useRef 获取元素和一些值。

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

    function UseRefExample() {
        const input = useRef(null)
        const handlerBtn = ()=>{
            input.current.value = 'hello'
            console.log(input)
        }

        const [text, setText] = useState('word')
        const textRef = useRef()
        
        useEffect(()=>{
            textRef.current = text
            console.log(`textRef.current:`,textRef.current)
        })


        return (
            <>
                <input ref={input} tpey="text" />
                <button onClick={handlerBtn}>click me</button>
                <br />
                <input 
                    value={text} 
                    onChange={(e)=>{setText(e.target.value)}} />
            </>
        )
    }

    export default UseRefExample
import React, { useRef, useState, useEffect } from 'react';

    function UseRefExample() {
        const input = useRef(null)
        const handlerBtn = ()=>{
            input.current.value = 'hello'
            console.log(input)
        }

        const [text, setText] = useState('word')
        const textRef = useRef()
        
        useEffect(()=>{
            textRef.current = text
            console.log(`textRef.current:`,textRef.current)
        })


        return (
            <>
                <input ref={input} tpey="text" />
                <button onClick={handlerBtn}>click me</button>
                <br />
                <input 
                    value={text} 
                    onChange={(e)=>{setText(e.target.value)}} />
            </>
        )
    }

    export default UseRefExample

自定义 Hooks

自定义 Hooks 必须使用以 use 开头。

自定义计算视图窗口大小例子。

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

    function UseWinSize() {
        const [size, setSize] = useState({
            width: document.documentElement.clientWidth,
            height: document.documentElement.clientHeight
        })

        const onResize = useCallback(()=>{
            setSize({
                width: document.documentElement.clientWidth,
                height: document.documentElement.clientHeight
            })
        }, [])

        useEffect(() => {
            window.addEventListener('resize', onResize)
            return () => {
                window.removeEventListener('resize', onResize)
            }
        })

        return size
    }

    function CustomHooks() {
        const size = UseWinSize()
        return (
            <>
                <div>页面Size:{ size.width } * {size.height }</div>
            </>
        )
    }

    export default CustomHooks
import React, { useState, useEffect, useCallback } from 'react';

    function UseWinSize() {
        const [size, setSize] = useState({
            width: document.documentElement.clientWidth,
            height: document.documentElement.clientHeight
        })

        const onResize = useCallback(()=>{
            setSize({
                width: document.documentElement.clientWidth,
                height: document.documentElement.clientHeight
            })
        }, [])

        useEffect(() => {
            window.addEventListener('resize', onResize)
            return () => {
                window.removeEventListener('resize', onResize)
            }
        })

        return size
    }

    function CustomHooks() {
        const size = UseWinSize()
        return (
            <>
                <div>页面Size:{ size.width } * {size.height }</div>
            </>
        )
    }

    export default CustomHooks