在这之前先设置一个 vscode 配置
jsconfig.json

  1. {
  2. "compilerOptions": {
  3. "baseUrl": "src",
  4. "paths": {
  5. "@/hooks": ["hooks/index"]
  6. }
  7. }
  8. }

这样在vscode 中 点击 别处引用的自定义hook 就能跳转了

useTitleHook

使浏览器标签页标题与文章标题保持一致

  1. import { useLayoutEffect, useState } from 'react'
  2. const useTitleHook = title => {
  3. const [state, setState] = useState()
  4. useLayoutEffect(() => {
  5. document.title = title
  6. setState(title)
  7. return () => {}
  8. }, [title])
  9. return state
  10. }
  11. export default useTitleHook

useHttpHook

fetch api 封装带有检测功能的hook,发送 Http 请求,并且返回 状态

  1. import { useState, useEffect } from 'react'
  2. import { Toast } from 'antd-mobile'
  3. const useHttpHook = ({
  4. url, //请求路径
  5. method = 'post', //请求方式
  6. headers, //请求头
  7. body = {}, //请求体
  8. watch = [], //useEffect 依赖项
  9. }) => {
  10. // eslint-disable-next-line no-unused-vars
  11. const [result, setResult] = useState()
  12. // eslint-disable-next-line no-unused-vars
  13. const [loading, setLoading] = useState(true)
  14. const Http = async () => {
  15. setLoading(true)
  16. const defaultHeader = {
  17. 'Content-Type': 'application/json',
  18. }
  19. let params
  20. if (method.toUpperCase() === 'GET') {
  21. params = undefined
  22. } else {
  23. params = {
  24. headers: {
  25. ...defaultHeader,
  26. headers,
  27. },
  28. method,
  29. body: JSON.stringify(body),
  30. }
  31. }
  32. return new Promise((resolve, reject) => {
  33. fetch('/api' + url, params)
  34. .then(res => res.json())
  35. .then(res => {
  36. if (res.status === 200) {
  37. resolve(res.data)
  38. setResult(res.data)
  39. } else {
  40. // Toast.show(res.errMsg)
  41. Toast.show({
  42. icon: 'fail',
  43. content: res.errMsg,
  44. })
  45. // console.log('TTT :', Toast)
  46. // console.log('RRRR', res.errMsg)
  47. reject(res.errMsg)
  48. }
  49. })
  50. .catch(err => {
  51. Toast.show(err)
  52. Toast.show({
  53. icon: 'fail',
  54. content: err,
  55. })
  56. reject(err)
  57. })
  58. .finally(() => {
  59. setLoading(false)
  60. })
  61. })
  62. }
  63. useEffect(() => {
  64. Http()
  65. // eslint-disable-next-line react-hooks/exhaustive-deps
  66. }, watch)
  67. return [result, loading]
  68. }
  69. export default useHttpHook