创建方式

  1. // 方法一
  2. const Hello = (props) => {
  3. return <div>{props.message}</div>
  4. }
  5. // 方法二
  6. const Hello = props => <div>{props.message}</div>
  7. //方法三
  8. function Hello(props){
  9. return <div>{props.message}</div>
  10. }

函数组件的缺点

函数组件没有state

但可以用 useState 这个API。

  1. const [n, setN] = React.useState(0)

没有生命周期

但有Hooks 来模拟

模拟componentDidMount

  1. useEffect(()=>{ console.log('第一次渲染变更') },[])

模拟componentDidUpdate

  1. // 如果想看每个数据 后面的那个就不写
  2. useEffect(()=>{ console.log('任意属性变更 ')})
  3. // 如果想看某一个或者某一些 就在后面的数组里面加上需要观察的组件
  4. useEffect(()=>{ console.log('n ')}, [n])

模拟 componentWillUnmount

  1. useEffect(()=>{
  2. // 组件在渲染的时候调用
  3. console.log('组件渲染了')
  4. // 组件在消亡的时候调用
  5. return ()=>{
  6. console.log('组件要死了')
  7. }
  8. })

render

  1. return (
  2. <div>{n}
  3. <button onClick={onClick}>+1</button>
  4. </div>
  5. )

return 里面的就是 render 的返回值

函数组件执行的时候,就相当于 constructor

自定义Hook

制作第一次变化时不算变化,第二次变化才算变化。

Hook自定义组件必须使用 use开头

导出 成为 useUpdate组件

  1. import {useEffect, useState} from 'react'
  2. const useUpdate = (fn, dep) => {
  3. const [count, setCount] = useState(0)
  4. useEffect(() => {
  5. setCount(x => x + 1)
  6. }, [dep])
  7. useEffect(() => {
  8. if (count > 1) {
  9. fn()
  10. }
  11. }, [count, fn])
  12. }
  13. export default useUpdate

引用

  1. import useUpdate from './useUpdate'