创建方式
// 方法一const Hello = (props) => {return <div>{props.message}</div>}// 方法二const Hello = props => <div>{props.message}</div>//方法三function Hello(props){return <div>{props.message}</div>}
函数组件的缺点
函数组件没有state
但可以用 useState 这个API。
const [n, setN] = React.useState(0)
没有生命周期
但有Hooks 来模拟
模拟componentDidMount
useEffect(()=>{ console.log('第一次渲染变更') },[])
模拟componentDidUpdate
// 如果想看每个数据 后面的那个就不写useEffect(()=>{ console.log('任意属性变更 ')})// 如果想看某一个或者某一些 就在后面的数组里面加上需要观察的组件useEffect(()=>{ console.log('n ')}, [n])
模拟 componentWillUnmount
useEffect(()=>{// 组件在渲染的时候调用console.log('组件渲染了')// 组件在消亡的时候调用return ()=>{console.log('组件要死了')}})
render
return (<div>{n}<button onClick={onClick}>+1</button></div>)
return 里面的就是 render 的返回值
函数组件执行的时候,就相当于 constructor
自定义Hook
制作第一次变化时不算变化,第二次变化才算变化。
Hook自定义组件必须使用 use开头
导出 成为 useUpdate组件
import {useEffect, useState} from 'react'const useUpdate = (fn, dep) => {const [count, setCount] = useState(0)useEffect(() => {setCount(x => x + 1)}, [dep])useEffect(() => {if (count > 1) {fn()}}, [count, fn])}export default useUpdate
引用
import useUpdate from './useUpdate'
