在这之前先设置一个 vscode 配置
jsconfig.json
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@/hooks": ["hooks/index"]
}
}
}
这样在vscode 中 点击 别处引用的自定义hook 就能跳转了
useTitleHook
使浏览器标签页标题与文章标题保持一致
import { useLayoutEffect, useState } from 'react'
const useTitleHook = title => {
const [state, setState] = useState()
useLayoutEffect(() => {
document.title = title
setState(title)
return () => {}
}, [title])
return state
}
export default useTitleHook
useHttpHook
对
fetch
api 封装带有检测功能的hook,发送 Http 请求,并且返回 状态
import { useState, useEffect } from 'react'
import { Toast } from 'antd-mobile'
const useHttpHook = ({
url, //请求路径
method = 'post', //请求方式
headers, //请求头
body = {}, //请求体
watch = [], //useEffect 依赖项
}) => {
// eslint-disable-next-line no-unused-vars
const [result, setResult] = useState()
// eslint-disable-next-line no-unused-vars
const [loading, setLoading] = useState(true)
const Http = async () => {
setLoading(true)
const defaultHeader = {
'Content-Type': 'application/json',
}
let params
if (method.toUpperCase() === 'GET') {
params = undefined
} else {
params = {
headers: {
...defaultHeader,
headers,
},
method,
body: JSON.stringify(body),
}
}
return new Promise((resolve, reject) => {
fetch('/api' + url, params)
.then(res => res.json())
.then(res => {
if (res.status === 200) {
resolve(res.data)
setResult(res.data)
} else {
// Toast.show(res.errMsg)
Toast.show({
icon: 'fail',
content: res.errMsg,
})
// console.log('TTT :', Toast)
// console.log('RRRR', res.errMsg)
reject(res.errMsg)
}
})
.catch(err => {
Toast.show(err)
Toast.show({
icon: 'fail',
content: err,
})
reject(err)
})
.finally(() => {
setLoading(false)
})
})
}
useEffect(() => {
Http()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, watch)
return [result, loading]
}
export default useHttpHook