index.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import {useLocation} from "react-router";
  2. import {useEffect, useState} from "react";
  3. import querystring from "query-string";
  4. export const getFirst = (item: string | null | Array<string | null>)=>{
  5. if (!item){
  6. return ''
  7. }
  8. if (Array.isArray(item)){
  9. return item.length ? item[0] ? item[0]: '' : ''
  10. }
  11. return item || ''
  12. }
  13. type ParseQueryType = {
  14. url: string
  15. query?: any
  16. route?: string
  17. fragmentIdentifier?: string
  18. }
  19. export function parseQuery<T>(): ParseQueryType{
  20. const fullUrl= window.location.href;
  21. const query = querystring.parseUrl(fullUrl, { parseFragmentIdentifier: true }) as ParseQueryType;
  22. if (query.fragmentIdentifier){
  23. const subQuery = querystring.parseUrl(query.fragmentIdentifier);
  24. Object.assign(query.query, subQuery.query);
  25. query.route = subQuery.url;
  26. }
  27. console.log('parseQuery', query)
  28. return query as {
  29. query: T,
  30. url: string
  31. }
  32. }
  33. /**
  34. * 解析route的参数
  35. */
  36. export function useQuery<T> (){
  37. const [query,setQuery] = useState<T>()
  38. const location = useLocation()
  39. const parseRouteQuery = ()=>{
  40. if (!location.search){
  41. return
  42. }
  43. const q = querystring.parse(location.search);
  44. setQuery(q as never)
  45. }
  46. useEffect(()=>{
  47. parseRouteQuery()
  48. },[location])
  49. useEffect(()=>{
  50. parseRouteQuery()
  51. },[])
  52. return query
  53. }
  54. export const cacheTo = (to='/')=>{
  55. localStorage.setItem('redirect_to', to)
  56. }
  57. export const getLastTo = (remove=false)=>{
  58. const to = localStorage.getItem(`redirect_to`);
  59. remove && localStorage.removeItem('redirect_to');
  60. return to ?? '/'
  61. }