React进入页面就获取数据hooks封装

87 阅读1分钟

目标

实现进入页面就获取数据的逻辑复用

封装

hooks/useInitState.ts 中:

// 导入用到的包
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import type { RootState } from '@/types/store'

// 创建 useInitialState 函数(自定义 hook)
export function useInitialState<StateName extends keyof RootState>(
  action: () => void,
  stateName: StateName
) {
  const dispatch = useDispatch()
  const state = useSelector((state: RootState) => state[stateName])

  useEffect(() => {
    dispatch(action())
  }, [dispatch, action])

  return state
}

使用

Profile/Edit.tsx 中:

import { useInitState } from '@/hooks/useInitState'

const ProfileEdti = () => {
  const { userProfile } = useInitState(getUserProfile, 'profile')
  // ...
}