context.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import {tabStore} from '@stores';
  2. import {useReducer} from 'react';
  3. import {createContext} from 'use-context-selector';
  4. type State = {
  5. key: string;
  6. url: string;
  7. label: string;
  8. }[];
  9. type Action =
  10. | {type: 'ADD'; payload: State[0]}
  11. | {type: 'REMOVE'; payload: string}
  12. | {type: 'CLEAR'};
  13. const defaultTab: State[0] = {key: '-1', url: '/main', label: '首页'};
  14. function reducer(state: State, action: Action): State {
  15. const {type} = action;
  16. const {key, dispatch} = tabStore.getState();
  17. switch (type) {
  18. case 'ADD': {
  19. const {payload} = action;
  20. dispatch(payload.key);
  21. const exist = state.find(val => val.key === payload.key);
  22. if (exist) {
  23. return state;
  24. }
  25. return [...state, payload];
  26. }
  27. case 'REMOVE': {
  28. const {payload} = action;
  29. const idx = state.findIndex(val => val.key === payload);
  30. if (idx < 0) return state;
  31. key === state[idx].key && dispatch(state[idx - 1].key);
  32. const nextState = [...state];
  33. nextState.splice(idx, 1);
  34. return nextState;
  35. }
  36. case 'CLEAR': {
  37. dispatch('-1');
  38. return [{...defaultTab}];
  39. }
  40. default:
  41. return state;
  42. }
  43. }
  44. export function useContextReudcer() {
  45. return useReducer(reducer, [defaultTab]);
  46. }
  47. export const context = createContext<ReturnType<typeof useContextReudcer>>([
  48. [],
  49. () => null,
  50. ]);