自定义Hook & 高阶组件

自定义Hook

自定义Hook: 将一些常用的、跨越多个组件的Hook功能,抽离出去形成一个函数,该函数就是自定义Hook。

自定义Hook,由于其内部需要使用Hook功能,所以它本身也需要按照Hook的规则实现:

  1. 函数名必须以use开头
  2. 调用自定义Hook函数时,应该放到顶层

例1:很多组件都需要在第一次加载完成后,获取某个api下的列表数据

//// useAllStudents.js
import { useEffect, useState } from 'react'

async function getAllStudents() {
  return await fetch('http://mock-api.com/DmgvxyKQ.mock/list')
    .then(response => response.json()).then(response => response.data.list)
}

// 自定义Hook
export default function useAllStudents() {
  const [students, setStudents] = useState([])
  // 第一次运行useEffect,先注册异步函数,等到页面渲染完成后再运行
  // 当页面渲染完成后,运行useEffect里注册的异步函数,拿到了数据,重新设置状态
  // 状态发生改变,函数重新运行,第二次运行useEffect时发现依赖项数组为空,所以不再执行异步函数
  // 这时候最后返回从后端请求回来的数据
  useEffect(() => {
    (async () => {
      const students = await getAllStudents()
      setStudents(students)
    })()
  }, [])
  // 第一次返回空数组
  // 第二次才返回从后端拿到的数据
  return students
}


//// App.js 使用自定义Hook 展示数据
import useAllStudents from './useAllStudents'
import React from 'react'

export default function App() {
  const students = useAllStudents()
  const list = students.map(item => 
  • {item}
  • ) return
      {list}
    }

    当然,使用高阶组件,也可实现相同的封装。但是,你会发现:

    1. 没有Hook方式来得优雅
    2. 高阶组件会导致组件层次嵌套变深

    高阶组件版:

    import React from 'react'
    
    async function getAllStudents() {
      return await fetch('http://mock-api.com/DmgvxyKQ.mock/list')
        .then(response => response.json()).then(response => response.data.list)
    }
    
    function withAllStudents(Comp) {
      return class AllStudentsWrapper extends React.Component {
    
        state = {
          students: []
        }
    
        async componentDidMount() {
          const students = await getAllStudents()
          this.setState({students})
        }
    
        render() {
          return 
        }
      }
    }
    

    例2:很多组件都需要在第一次加载完成后,启动一个计时器,然后在组件销毁时卸载

    //// userTimer.js
    import { useEffect } from 'react'
    
    /* eslint "react-hooks/exhaustive-deps": "off" */
    
    /**
     * 组件首次渲染后,启动一个interval计时器
     * 组件卸载后,清除该计时器
     * @param fn
     * @param duration
     */
    export default (fn, duration) => {
      useEffect(() => {
        const timer = setInterval(fn, duration)
        return () => {
          clearInterval(timer)
        }
      }, [])
    }
    
    
    //// Test.js
    import React from 'react'
    import useTimer from './useTimer'
    
    export default function Test() {
      useTimer(() => {
        console.log('Test组件的一些副作用操作')
      }, 1000)
      return 

    Test组件

    }

    你可能感兴趣的:(自定义Hook & 高阶组件)