import { RootState } from '@/types/store'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
// 页面中代码块高亮
import hljs from 'highlight.js'
// 代码高亮的主题
import 'highlight.js/styles/dark.css'
/**
*
* 函数封装的基本思想:
1. 将相同的逻辑直接拷贝到函数中
2. 不同的数据或逻辑通过函数参数传入
3. 需要返回数据,就通过函数返回值返回
* @param actionFn 异步action函数
* @param stateName redux数据模块名
* @returns
*/
export function useInitState<StateName extends keyof RootState>(actionFn: () => void, stateName: StateName) {
const dispatch = useDispatch()
useEffect(() => {
// 1. 分发异步action获取数据,存到redux
dispatch<any>(actionFn())
}, [dispatch, actionFn])
// 2. 从redux获取数据
const state = useSelector((state: RootState) => state[stateName])
// 返回外部需要的数据
return state
}
/**
* 对页面中代码块执行高亮处理
*/
export function useHighlightCode() {
useEffect(() => {
// 忽略警告
hljs.configure({
ignoreUnescapedHTML: true,
})
// 找到页面中所有代码块,执行高亮方法
document.querySelectorAll<HTMLElement>('pre code').forEach((el) => {
// 对代码块执行高亮处理=》添加元素包裹和类名
hljs.highlightElement(el)
})
}, [])
}
src/hooks/index.ts中
使用
const user = useInitState(editProfileAction, "profileReducer");