context.ts 983 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import {createPageContext} from '@hooks';
  2. import {Dispatch, useReducer} from 'react';
  3. import {createContext} from 'use-context-selector';
  4. //#region 搜索参数
  5. type State = {
  6. code: string;
  7. name: string;
  8. isSearching: boolean;
  9. };
  10. type Action =
  11. | {
  12. type: 'SEARCH',
  13. payload: Omit<State, 'isSearching'>,
  14. }
  15. | {
  16. type: 'CHANGE_SEARCH_STATE',
  17. payload: boolean,
  18. };
  19. function reducer(state: State, action: Action): State {
  20. const {type} = action;
  21. switch (type) {
  22. case 'SEARCH':
  23. return {...state, ...action.payload};
  24. case 'CHANGE_SEARCH_STATE':
  25. return {...state, isSearching: action.payload};
  26. default:
  27. return state;
  28. }
  29. }
  30. function initState(): State {
  31. return {code: '', name: '', isSearching: false};
  32. }
  33. export function useContextReducer() {
  34. return useReducer(reducer, initState());
  35. }
  36. export const context = createContext<[State, Dispatch<Action>]>([initState(), () => null]);
  37. //#endregion
  38. export const pageContext = createPageContext();