React函数组件

112 阅读1分钟

一 创建方式

//实现加一功能
const App=()=>{
    const [n,setN]=React.useState(0);
    const add=()=>{
        setN(n+1);
    }
    return(
        <div>{n}
            <button onClick={add}>+1</button>
        </div>
    )
}

二 函数组件代替class组件

  1. 没有state
    React v16.8.0 推出Hooks API 中的useState可以解决此问题
  1. 没有生命周期
    React v16.8.0 推出的Hooks API 中的useEffect可以解决此问题

三 使用useEffect模拟生命周期

  1. 模拟componentDidMount
    useEffect(()=>{
        console.log('渲染了')
    },[])
  1. 模拟componentDidUpdate
    //初次渲染时的更新也会触发此钩子,这点不同于componentDidUpdate
    
    //m或n更新时触发
    useEffect(()=>{
        console.log('m或n更新了')
    },[m,n])
    //不传参数则表示任意属性变更了都触发此钩子
    useEffect(()=>{
        console.log('任意属性变了')
    })
    
    //自定义Hook来完全模拟componentDidUpdate
    const useUpdate=(fn,dep)=>{
        const [count,setCount]=useState(0);
        //当dep变化了,count+1
        useEffect(()=>{
            setCount(count=>count+1)
        },[dep]);
        
        useEffect(()=>{
            //初次渲染时count由0变为1
            //之后count会一直大于1
            if(count>1){
                fn();
            }
        },[fn,count])
    }
  1. 模拟componentWillUnmount
    useEffect(()=>{
        return ()=>{
            console.log('组件将要销毁')
        }
    })
  1. 其他生命周期怎么模拟 (1) constructor,函数组件执行的时候就相当于constructor
    (2) shouldComponentUpdate,使用React.memo和useMemo即可解决
    (3) render,函数组件的返回值就是render的返回值

四 总结

函数组件不用this,且书写简单很多。但是没有state和生命周期,需要我们自己使用Hooks模拟